如何在 Spring Boot 2 中保护具有角色的执行器端点?

Den*_*nov 7 java spring spring-security spring-boot 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

但是当我去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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*cio 10

如果您的应用程序是资源服务器,则不需要 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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