Spring Boot Actuator Endpoints security doesn't work with custom Spring Security Configuration

后端 未结 4 1423
[愿得一人]
[愿得一人] 2021-02-05 15:19

This is my Spring Boot 1.5.1 Actuator application.properties:

#Spring Boot Actuator
management.contextPath: /actuator
management.security.roles=R_0
         


        
4条回答
  •  悲哀的现实
    2021-02-05 15:49

    I'm coming at this from a Reactive Spring Boot 2.x app and had this problem and solved it by updating the WebSecurityConfig.securityWebFilterChain as well as SecurityContextRepository.load to include /actuator/** as follows:

    public class WebSecurityConfig {
      private AuthenticationManager authenticationManager;
    
      private SecurityContextRepository securityContextRepository;
    
      @Autowired
      public WebSecurityConfig(AuthenticationManager authenticationManager, SecurityContextRepository securityContextRepository) {
        this.authenticationManager = authenticationManager;
        this.securityContextRepository = securityContextRepository;
      }
    
      @Bean
      public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
          .exceptionHandling()
          .authenticationEntryPoint((swe, e) -> Mono.fromRunnable(() -> {
            swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
          })).accessDeniedHandler((swe, e) -> Mono.fromRunnable(() -> {
            swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
          })).and()
          .csrf().disable()
          .formLogin().disable()
          .httpBasic().disable()
          .authenticationManager(authenticationManager)
          .securityContextRepository(securityContextRepository)
          .authorizeExchange()
          .pathMatchers("/actuator/**").permitAll()
          .anyExchange().authenticated()
          .and().build();
      }
    

    as well as updating

    @Slf4j
    @Component
    public class SecurityContextRepository implements ServerSecurityContextRepository {
    
      private AuthenticationManager authenticationManager;
    
      public SecurityContextRepository(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
      }
    
      @Override
      public Mono save(ServerWebExchange swe, SecurityContext sc) {
        return Mono.error(new UnsupportedOperationException("Not supported"));
      }
    
      @Override
      public Mono load(ServerWebExchange swe) {
        ServerHttpRequest request = swe.getRequest();
    
        if (request.getPath().value().startsWith("/actuator") ) {
          return Mono.empty();
        }
        // other authentication logic here
      }
    

提交回复
热议问题