当前位置: 首页 > 知识库问答 >
问题:

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

督德明
2023-03-14

我将spring boot rest服务迁移到使用spring boot 2.0.2,并面临执行器endpoint的问题。我知道SpringBoot删除了Spring2.0.2中执行器框架的自动配置安全性。因此,我认为我必须指定安全性才能访问这些endpoint,但我已经为我的web服务配置了安全性以使用JWT。请建议我如何在spring boot 2.0.2中启用执行器endpoint,并在不影响Jwt的情况下为执行器endpoint配置安全性

聚甲醛

<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开机1.5工作。十、

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

处理程序:Type=null

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

共有1个答案

尤祖鹤
2023-03-14

如果pom中有http安全性,则必须覆盖配置otheriwse默认设置,它将需要身份验证,并将对所有endpoint抛出401。

因此,根据您的endpoint和角色,您应该具有以下配置和句柄,您可能还必须调用jwtAccessTokenConverterConfiguration,以获取需要检查身份验证的endpoint。(我不认为,这个jwtAccessTokenConverterConfiguration甚至被调用,您调试了吗?)

下面的示例将通过身份验证的所有endpoint,并根据需要进行修改。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

}
 类似资料:
  • 我正在使用Jersey编写REST web服务,并尝试编写一组单元测试,以使用Jersey测试框架测试该服务。 然而,我使用HTTP身份验证和SecurityContext作为我的web服务的一部分,我在设置JTF以允许我测试这些方面时遇到了问题。我可以在请求中发送身份验证信息,但如何配置它以了解我希望设置的不同角色和用户? 我目前正在使用Jetty(通过JettyTestContainerFac

  • herosphpphp的配置信息都在app/configs文件夹中 configs目录中包含了该应用所有的相关配置文档: env 跟环境相关的配置,app配置,数据库配置。包含了三个环境, dev(开发), test(测试), prod(生产) autoload.config.php 自定义需要自动加载的类的配置 beans beans服务配置文件目录 models 模型配置文件夹 session

  • 本文向大家介绍Mysql从5.6.14安全升级至mysql5.6.25的方法,包括了Mysql从5.6.14安全升级至mysql5.6.25的方法的使用技巧和注意事项,需要的朋友参考一下 服务器上Mysql的版本为:社区版的mysql-community-server-5.6.14。近日局方对服务器进行漏洞扫描,发现zhyh08上的mysql存在几个高危漏洞,要求进行修复。受这几个漏洞影响的主要是

  • 问题内容: 我正在淘汰Java库中的所有硬编码值,并且想知道哪种框架最好(就零或接近零的配置而言)来处理运行时配置?我希望使用基于XML的配置文件,但这不是必需的。 如果您有框架方面的实践经验,请仅作答复。我不是在寻找例子,而是经验…… 问题答案: 如果您的硬编码值只是简单的键值对,则应查看java.util.Properties。它比xml简单得多,易于使用,并且实现起来很麻烦。 如果您正在使用

  • 我正在使用micronaut框架,并试图从对于标准测试用例,我可以配置datastax驱动程序 然而,我找不到一种方法来提供与方法 我看到了https://github.com/micronaut-projects/micronaut-core/blob/dc8c423be1979817c9c8f53440f3b87e775523b2/configurations/cassandra/src/ma

  • phpGrace 框架部署到非项目目录 将 phpGrace 框架部署到非项目目录可以使得系统更安全,也可以实现多个项目公用一套框架的目的。步骤如下: 1、将 phpGrace 文件夹放到非项目目录,如 : D:\phpGrace 2、改写入口文件,类似以下代码: <?php include 'D:\phpGrace\phpGrace.php'; 改变app目录名称 将 app 核心目录名改写也可