从 Spring Boot 1.5 升级时为 Spring Boot 2.0 acuator 框架配置安全性

Posted

技术标签:

【中文标题】从 Spring Boot 1.5 升级时为 Spring Boot 2.0 acuator 框架配置安全性【英文标题】:configure security for Spring Boot 2.0 acuator framework when upgraded from spring boot 1.5 【发布时间】:2019-02-17 16:27:06 【问题描述】:

我迁移了我的 spring boot rest 服务以使用 spring boot 2.0.2 并面临执行器端点的问题。我知道 spring boot 在 spring 2.0.2 中删除了执行器框架的自动配置安全性。所以我认为我必须指定安全性才能访问这些端点,但我已经为我的 Web 服务配置了安全性以使用 JWT。请建议我如何在 Spring Boot 2.0.2 中启用执行器端点,并为执行器端点配置安全性而不影响 Jwt

pom

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>
<properties>
    <jacoco.version>0.7.8</jacoco.version>
    <java.version>1.8</java.version>
    <mockito.version>2.7.22</mockito.version>
    <mybatis.version>3.4.4</mybatis.version>
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
</properties>
<build>
    <finalName>$project.artifactId</finalName>
    <resources>
        <resource>
            <filtering>true</filtering>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <!-- Uncomment this plugin after you have initialized the git repo. -->
        <!-- 
        <plugin>
            <groupId>pl.project13.maven</groupId>
            <artifactId>git-commit-id-plugin</artifactId>
        </plugin>
        -->
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>$jacoco.version</version>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                        <goal>check</goal>
                        <goal>report</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <rules>
                    <rule>
                        <element>CLASS</element>

                        <limits>
                            <limit>
                                <counter>LINE</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>1.00</minimum>
                            </limit>
                            <limit>
                                <counter>BRANCH</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>1.00</minimum>
                            </limit>
                        </limits>
                    </rule>
                </rules>
            </configuration>
        </plugin>
    </plugins>
</build>
<reporting>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>$jacoco.version</version>
            <reportSets>
                <reportSet>
                    <reports>
                        <report>report</report>
                    </reports>
                </reportSet>
            </reportSets>
        </plugin>
    </plugins>
</reporting>
<dependencies>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.2.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>com.ibm.db2.jcc</groupId>
        <artifactId>db2jcc_license_cisuz</artifactId>
        <version>DB2V11</version>
    </dependency>
    <dependency>
        <groupId>com.ibm.db2.jcc</groupId>
        <artifactId>db2jcc4</artifactId>
        <version>4.19.26</version>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.skyscreamer</groupId>
        <artifactId>jsonassert</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>$mockito.version</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>$mybatis.version</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>$mybatis.spring.version</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-properties-migrator</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

集成测试yaml

mybatis:
  configuration-properties:
               schema: abcd

spring:
  datasource:
     url: 
     username: 
     password: 

management:
  endpoints:
    web:
     exposure:
       include: "*"

安全配置如下

 @Configuration
 @EnableResourceServer
 public class SecurityConfiguration implements 
      JwtAccessTokenConverterConfigurer 

@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws 
  Exception 


 auth.inMemoryAuthentication().withUser("management").password("cfh5r64r 
  bvc54r").roles("ACTUATOR");



@Bean
public FilterRegistrationBean corsFilter() 
    // Set CORS configuration to allow cross-origin requests by default.
    // Addtionally add the HTTP OPTIONS method for pre-flight requests.
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.applyPermitDefaultValues();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.addAllowedMethod(HttpMethod.GET);
    corsConfiguration.addAllowedMethod(HttpMethod.POST);
    corsConfiguration.addAllowedMethod(HttpMethod.PUT);
    corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);

    UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(
            new CorsFilter(urlBasedCorsConfigurationSource));
    filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);

    return filterRegistrationBean;



@Override
public void configure(JwtAccessTokenConverter converter) 
    converter.setAccessTokenConverter(new DefaultAccessTokenConverter() 


        @Override
        public OAuth2Authentication extractAuthentication(Map<String, ?> 
           map) 
            Object i = map.get();
            Object e = map.get();

            if (issuerClaim == null || !issuer.equals(issuerClaim) || expirationClaim == null) 
                throw new InvalidTokenException("");
            

            return super.extractAuthentication(map);
        
    );

我正在尝试编写如下集成测试

@RunWith(SpringRunner.class)
 @SpringBootTest(webEnvironment = WebEnvironment.MOCK)
 @AutoConfigureMockMvc
@ActiveProfiles("it")
@DirtiesContext
 public class SecurityConfigurationIT 

@Test
@WithMockUser(roles = VALID_ACTUATOR_ROLE)
public void should_be_authorized_for_actuator() throws Exception 
    mockMvc.perform(get(LOGGERS).header(HttpHeaders.ORIGIN, 
     ORIGIN)).andExpect(status().isOk())                 
       .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, 
      ORIGIN));


@Test
@WithMockUser(roles = INVALID_ACTUATOR_ROLE)
public void should_fail_as_forbidden_for_actuator() throws Exception 
    mockMvc.perform(get(LOGGERS).header(HttpHeaders.ORIGIN, 
   ORIGIN)).andExpect(status().isForbidden())

   .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, 
    ORIGIN));

当我尝试运行它时得到 401 但这在 spring boot 1.5.x 中工作

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /actuator/info
   Parameters = 
      Headers = Origin=[test.com]
         Body = null
Session Attrs = 

处理程序: 类型 = 空

Async:
Async started = false
 Async result = null

 Resolved Exception:
         Type = null

     ModelAndView:
    View name = null
         View = null
        Model = null

  FlashMap:
   Attributes = null

  MockHttpServletResponse:
       Status = 401
Error message = null
      Headers = Vary=[Origin, Access-Control-Request-Method, Access- 
        Control-Request-Headers], Access-Control-Allow-Origin=[test.com], 
     Access-Control-Allow-Credentials=[true], Cache-Control=[no-store], 
   Pragma=[no-cache], WWW-Authenticate=[Bearer realm=", 
 error="unauthorized", error_description="Full 
       authentication is required to access this resource"], Content-Type= 
   [application/json;charset=UTF-8], X-Content-Type-Options=[nosniff], X- 
      XSS-Protection=[1; mode=block], X-Frame-Options=[DENY]
 Content type = application/json;charset=UTF-8
         Body = "error":"**unauthorized","error_description":"Full 
     authentication is required to access this resource"**
Forwarded URL = null

重定向的 URL = null

【问题讨论】:

哪个测试失败了? LOGGERS 的价值是什么?错误指出 URI 是 /actuators/info 但变量是 LOGGERS 似乎很奇怪。您的测试是否与异常输出一致? 您能否展示一下您的 http 安全配置类?主要是http覆盖方法,你定义了什么规则? @Rob 感谢您的关注。两个测试都失败了。抱歉,我正在尝试不同的端点,但所有端点都失败了。它为所有这些提供 401 状态。 @kj007 我没有 http 安全配置类。即使我有两个 securityConfiguration 类,一个扩展 websecurityAdapter,一个实现 jwtAccessTokenConverterConfiguration,拥有 http 安全配置类是否合法? 【参考方案1】:

如果您的 pom 中有 http 安全性,则必须覆盖配置,否则默认情况下它将需要身份验证,并且会为所有端点抛出 401。

所以您应该根据您的端点和角色进行以下配置和处理,您可能还需要调用jwtAccessTokenConverterConfiguration 来获取需要检查身份验证的端点。 (我不认为,这个jwtAccessTokenConverterConfiguration 甚至被调用了,你调试了吗?)

下面是示例,它将通过身份验证的所有端点,根据您的需要进行修改。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http
                .authorizeRequests()
                .antMatchers("/**").permitAll();
    


【讨论】:

是的,我得到了其他适用于 JWT 的集成测试,我还为应用程序端点调用了 jwtAccessTokenConverterConfiguration,它工作正常。而且我认为我的 pom 中没有 http 安全性。 你能告诉我扩展网络安全适配器的类吗?或者,您甚至可以通过定义 false 或覆盖 web-security 来处理执行器端点的基本身份验证来禁用应用程序属性中的执行器安全性。 我没有扩展网络安全适配器的类。我尝试禁用敏感道具但没有运气。

以上是关于从 Spring Boot 1.5 升级时为 Spring Boot 2.0 acuator 框架配置安全性的主要内容,如果未能解决你的问题,请参考以下文章

从 Spring Boot 1.5 升级到 2.0 - 无法在只读事务中执行 UPDATE

多模块 Gradle 项目 - 从 Spring-Boot 1.5 迁移到 2.1

将 Spring Boot 1.5 升级到 2 <sec:authorize> 不起作用

Spring Boot 版本从 2.1.6 升级到 2.2.1 和 spring-cloud 问题

Spring Boot 2.0干货系列:Spring Boot1.5X升级到2.0指南

雪球 Spring Boot 2.0 升级经验谈