Spring Security CSRF 禁用不起作用

问题描述 投票:0回答:1

我想使用基本身份验证保护

/actuator/shutdown
端点。我有一个
UserDetailsService
的实现,我的安全类如下所示:

@Configuration
public static class ActuatorWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

  @Autowired
  UserProvider userProvider;

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(new UserDetailsServiceCustom(userProvider)).passwordEncoder(new BCryptPasswordEncoder(12));
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
       .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.authorizeRequests()
       .antMatchers("/actuator/shutdown").authenticated().and().httpBasic();
  }
}

我在属性中启用了这样的关闭端点:

management:
  endpoints:
    web:
      exposure:
        include: shutdown
  endpoint:
    shutdown:
      enabled: true

当我执行

POST /actuator/shutdown
时,我收到 403 FORBIDDEN 并且使用调试器,我发现
UserDetailsServiceCustom
方法根本没有被触发,但是如果我尝试
GET /actuator/shutdown
我收到 405 并且
UserDetailsServiceCustom
中的方法被正确触发,所以这意味着我可以访问此端点,但有些东西阻碍了 POST。我用谷歌搜索了很多,发现这是因为 CSRF,但正如你所看到的,我已经禁用了它。我还尝试添加
web.ignoring().antMatchers("/actuator/shutdown")
但这样任何人都可以访问此端点。

所以我的问题是如何启用使用我的数据库用户作为此端点的基本身份验证?

更新 好吧,问题不在于 HttpSecurity 配置或 CSRF,而在于我如何错误地实现了multiple HttpSecurity

java spring spring-security basic-authentication
1个回答
1
投票

 http.csrf().disable()
在 Spring Boot 3.x.x 中不起作用。您应该尝试以下行。

@Configuration
@EnableWebSecurity
public class SpringFilterChainConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable);
        http.cors(AbstractHttpConfigurer::disable);

        return http
                .authorizeHttpRequests(request -> request
                        .requestMatchers(HttpMethod.POST, "/api/users").permitAll()
                        .requestMatchers(HttpMethod.POST, "/api/users/login").permitAll()
                        .anyRequest()
                        .authenticated()
                ).build();
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.