How to secure actuator endpoints with role in Spring Boot 2?

Denis Stephanov :

Can you help to secure actuator endpoints in Spring Boot 2? I checked migration guide but it doesn't help me.

Here is my security config:

@Configuration
@EnableWebSecurity
public class SecConfig extends WebSecurityConfigurerAdapter {

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

}

but when I go to http://localhost:8080/actuator/health it loads without login. Other endpoints with prefix /actuator doesn't require login as well. What I did wrong?

I also add OAuth with this configuration:

@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();
    }
}
Francesc Recio :

If your application is a resource server you don't need the SecConfig class.

So if you remove it, in your ResourceServerConfig class you can secure the actuators and just let admin through:

@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();
    }
}

I add .anyRequest().authenticated() to secure the rest of the application endpoints.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79162&siteId=1