Spring Security总是为POST请求返回HTTP 403

ezykj2lf  于 9个月前  发布在  Spring
关注(0)|答案(1)|浏览(112)

我试图运行一个现有的Sping Boot 3应用程序,我发现很难,因为Spring Security总是为除了/health/info之外的所有请求返回HTTP 403。
错误响应:

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

字符串
pom文件:

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


执行器安全等级:

@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


这是否需要在请求中包含一个基本的Auth认证头?我觉得这很令人困惑,因为GET请求的认证没有任何问题。
任何建议将不胜感激。

drkbr07n

drkbr07n1#

检查此403是否由缺少CSRF令牌引起。这可以通过调整application.yamlCsrfFilter的日志记录级别来完成:

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

字符串
您也可以尝试禁用CSRF保护(不一定推荐):

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


建议的解决方案是在POST请求中包含有效的CSRF令牌。

相关问题