Protect Actuator endpoints with user/password while granting public access for RestControllers

梦想与她 提交于 2020-05-28 03:34:07

问题


I updated an already existing application from Spring Boot 1.3 to 2.0.1. This application makes use of the Actuator and exposes a REST-style API.

In Boot 1.3 the API could be used without authentication and the actuator endpoint was configured to be password protected:

security.user.name=foo
security.user.password=bar
security-user.role=ADMIN

I updated this like documented in the configuration changelog and renamed the entries from security.user.name to spring.security.user.name and alike.

But when I try to curl my API, I am denied because I do not provide credentials:

In the Spring Blog I found a possible solution how to configure Spring Security on a detailled level:

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()
  ...

but this is more fine-grained than I need and I am looking for an application.properties based solution.

Is there a way to solve this without additional code ?


回答1:


When you set spring.security.user.name and spring.security.user.password, you are configuring form login via spring-security for the whole application, including the Actuator endpoints.

Unfortunately, in Spring Boot 2.0 you cannot set a different username/password or disable authentication for the Actuator endpoints using the properties. This means you have to explicitly allow the actuator endpoints through Security configuration.

Through spring-security, you can also allow public access to your endpoints and require credentials for the actuator endpoints very easily:

@Configuration
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {

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

(I assumed you were using WebMvc, not WebFlux, which is a bit different)

Verify that you have the following in the application.properties:

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

See here for a quick and nice explanation between the differences in Actuator in Spring 1.x vs 2.0.



来源:https://stackoverflow.com/questions/50168650/protect-actuator-endpoints-with-user-password-while-granting-public-access-for-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!