Spring boot 在授予RESTController的公共访问权限时,使用用户/密码保护执行器端点

Spring boot 在授予RESTController的公共访问权限时,使用用户/密码保护执行器端点,spring-boot,spring-security,spring-restcontroller,spring-boot-actuator,Spring Boot,Spring Security,Spring Restcontroller,Spring Boot Actuator,我将一个已经存在的应用程序从Spring Boot 1.3更新为2.0.1。此应用程序使用执行器并公开REST样式的API 在Boot 1.3中,API可在无需验证的情况下使用,且致动器端点配置为密码保护: security.user.name=foo security.user.password=bar security-user.role=ADMIN 我更新了中记录的类似内容,并将条目从security.user.name重命名为spring.security.user.name等 但当我

我将一个已经存在的应用程序从Spring Boot 1.3更新为2.0.1。此应用程序使用执行器并公开REST样式的API

在Boot 1.3中,API可在无需验证的情况下使用,且致动器端点配置为密码保护:

security.user.name=foo
security.user.password=bar
security-user.role=ADMIN
我更新了中记录的类似内容,并将条目从
security.user.name
重命名为
spring.security.user.name

但当我尝试
curl
我的API时,我被拒绝了,因为我没有提供凭据:

在中,我找到了一个可能的解决方案,即如何在详细级别上配置Spring安全性:

http
    .authorizeRequests()
        // 1
        .requestMatchers(EndpointRequest.to("status", "info"))
            .permitAll()
        // 2
        .requestMatchers(EndpointRequest.toAnyEndpoint())
            .hasRole("ACTUATOR")
        // 3 
        .requestMatchers(StaticResourceRequest.toCommonLocations())
            .permitAll()
        // 4
        .antMatchers("/**")
            .hasRole("USER")
    .and()
  ...
但这比我需要的更细粒度,我正在寻找一个基于
application.properties
的解决方案


有没有一种方法可以解决这个问题而不需要额外的代码?

当您设置
spring.security.user.name
spring.security.user.password
时,您可以通过
spring security
为整个应用程序配置表单登录,包括执行器端点

不幸的是,在Spring Boot 2.0中,您无法使用属性设置其他用户名/密码或禁用执行器端点的身份验证。这意味着您必须通过安全配置明确允许执行器端点

通过
spring security
,您还可以允许公众访问您的端点,并非常容易地要求执行器端点的凭据:

@Configuration
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {

    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/actuator/**").hasRole("ACTUATOR")
                .anyRequest().permitAll();
    }
}
(我假设您使用的是WebMvc,而不是WebFlux,这有点不同)

验证
应用程序.属性中是否有以下内容:

spring.security.user.name=user
spring.security.user.password=pass
spring.security.user.roles=ACTUATOR,USER   # and others, if you like

management.endpoint.health.roles=ACTUATOR

有关Spring 1.x与2.0中执行器的差异的快速而准确的解释,请参阅。

对于Spring Boot 2.0,当我们覆盖
WebSecurity配置适配器的
configure
方法时,所有现有的安全性都会后退,我们可以提供自定义的安全性。在您的情况下,您只需要验证执行器端点,可以按如下方式执行:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

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

}

应用程序.properties
文件中不需要任何更改。

当我想要所有其他-这意味着那些不等于
/exactor
-未受保护时,这需要什么样的外观?此配置正是如此!它仅对以
/exactor
开头的路径要求执行器角色。对于其他一切,它不需要任何凭证。今天我终于有时间尝试了。不幸的是,当执行器也请求密码时,REST服务仍然受到保护。该类包含在JAR中,但显然未使用/未工作。使用了我存储在同一个包中的带有@Configuration注释的其他类,我可以在bean中看到它们。好吧,您必须确保此配置作为bean可用,否则它将无法工作。我用2.0.2.0版本测试了这个。尝试创建一个裸体项目进行验证。如何编写测试来检查验证功能?