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

ezykj2lf  于 2024-01-09  发布在  Spring
关注(0)|答案(1)|浏览(226)

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

  1. {
  2. "timestamp": "2023-11-28T21:31:49.646+00:00",
  3. "status": 403,
  4. "error": "Forbidden",
  5. "path": "/test-service/v1/test"
  6. }

字符串
pom文件:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>


执行器安全等级:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class ActuatorSecurityConfig {
  4. @SuppressWarnings("squid:S2068")
  5. private static final int BCRYPT_STRENGTH = 16;
  6. @Value("${metrics_password}")
  7. private String metricsPassword;
  8. @Bean
  9. public InMemoryUserDetailsManager userDetailsManager() {
  10. BCryptPasswordEncoder encoder = passwordEncoder();
  11. String result = encoder.encode(metricsPassword);
  12. UserDetails user = User
  13. .withUsername("actuator")
  14. .password(result)
  15. .roles("ACTUATOR_ADMIN")
  16. .build();
  17. return new InMemoryUserDetailsManager(user);
  18. }
  19. @Bean
  20. public static BCryptPasswordEncoder passwordEncoder() {
  21. return new BCryptPasswordEncoder(BCRYPT_STRENGTH);
  22. }
  23. @Bean
  24. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  25. return http
  26. .authorizeHttpRequests()
  27. .anyRequest().permitAll()
  28. .and().httpBasic()
  29. .and()
  30. .build();
  31. }
  32. }


application.properties

  1. metrics_password = password123


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

drkbr07n

drkbr07n1#

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

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

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

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


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

相关问题