如何通过Spring Boot 2中的角色保护执行器端点?

时间:2019-05-13 18:00:38

标签: java spring spring-boot spring-security spring-boot-actuator

您能帮助保护Spring Boot 2中的执行器端点吗?我查看了迁移指南,但对我没有帮助。

这是我的安全配置:

@Configuration
@EnableWebSecurity
public class SecConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")    
                .anyRequest().authenticated();
    }

}

但是当我转到http://localhost:8080/actuator/health时,它将加载而无需登录。前缀为/actuator的其他端点也不需要登录。我做错了什么?

我还使用以下配置添加了OAuth:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients
            .inMemory()
                .withClient("client-id")
                    .scopes("read", "write")
                    .authorizedGrantTypes("password")
                    .secret("xxxxxx")
                    .accessTokenValiditySeconds(6000);
}
}

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/ajax/**").authenticated()
                .and()
            .csrf()
                .disable();
    }
}

2 个答案:

答案 0 :(得分:3)

如果您的应用程序是资源服务器,则不需要SecConfig类。

因此,如果您将其卸下,则可以在您的ResourceServerConfig类中保护执行器,并让管理员通过:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/ajax/**").authenticated()           
                .antMatchers("/actuator/**").hasRole("ADMIN")  
                .anyRequest().authenticated()  
                .and()
            .csrf()
                .disable();
    }
}

我添加.anyRequest().authenticated()来保护其余应用程序端点。

答案 1 :(得分:0)

您可以尝试以下配置

@Configuration
public class SecConfig extends WebSecurityConfigurerAdapter {

public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/actuator/**").hasRole("ACTUATOR")
            .anyRequest().permitAll();
}
}

验证application.properties中是否具有以下内容:

spring.security.user.name=user
spring.security.user.password=pass
spring.security.user.roles=ACTUATOR,USER   # or any other role 
management.endpoint.health.roles=ACTUATOR