Search code examples
spring-bootspring-securityspring-boot-actuator

Spring Security always return HTTP 403 for POST requests


I'm trying to run an existing Spring Boot 3 application, where I'm finding it hard as Spring Security always returning HTTP 403 for all the requests except for /health and /info.

Error response :

{
  "timestamp": "2023-11-28T21:31:49.646+00:00",
  "status": 403,
  "error": "Forbidden",
  "path": "/test-service/v1/test"
}

pom file :

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

ActuatorSecurity class :

@Configuration
@EnableWebSecurity
public class ActuatorSecurityConfig {

  @SuppressWarnings("squid:S2068")
  private static final int BCRYPT_STRENGTH = 16;

  @Value("${metrics_password}")
  private String metricsPassword;

  @Bean
  public InMemoryUserDetailsManager userDetailsManager() {
     BCryptPasswordEncoder encoder = passwordEncoder();
     String result = encoder.encode(metricsPassword);
     UserDetails user = User
        .withUsername("actuator")
        .password(result)
        .roles("ACTUATOR_ADMIN")
        .build();

    return new InMemoryUserDetailsManager(user);
  }

  @Bean
  public static BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(BCRYPT_STRENGTH);
  }

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests()
        .anyRequest().permitAll()
        .and().httpBasic()
        .and()
        .build();
  }
}

application.properties

metrics_password = password123

Does this require to include a Basic Auth authentication header in the request? I find it confusing as GET requests are authenticated without any issue.

Any suggestions would be appreciated.


Solution

  • Check if this 403 is caused by missing CSRF token. This can be done by adjusting logging level of CsrfFilter in application.yaml:

    logging.level:
        org.springframework.security.web.csrf.CsrfFilter: debug
    

    You can also try to disable CSRF protection (not necessarily recommended):

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            // ...
            .csrf(c -> c.disable())
    

    The recommended soulution would be to include the valid CSRF token in your POST requests.