You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security配置后POST /hi仍需认证,请求排查解决

问题原因

你多次调用了authorizeHttpRequests()方法,这会导致Spring Security创建多个权限验证过滤器(AuthorizationFilter)。第一个过滤器会允许POST /hi和GET /hello通过,但第二个过滤器会再次对请求进行校验,而POST /hi不匹配第二个过滤器里的/authenticate规则,此时第二个过滤器会默认要求所有未匹配的请求必须认证,最终导致POST /hi被拦截。

解决方法

将所有请求权限规则合并到同一个authorizeHttpRequests()配置块中,确保规则从上到下匹配(优先匹配的规则放在前面),同时可根据业务需求添加anyRequest().authenticated(),指定除免认证接口外的其他请求都需要认证。

修改后的SecurityFilterChain配置

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
    return http.csrf().disable()
            .authorizeHttpRequests()
            // 配置免认证接口
            .requestMatchers("/hello").permitAll()
            .requestMatchers(HttpMethod.POST, "/hi").permitAll()
            // 配置需要认证的接口
            .requestMatchers("/authenticate").authenticated()
            // 其他所有请求需认证(根据业务场景选择是否保留)
            .anyRequest().authenticated()
            .and().formLogin()
            .and().logout()
            .and().build();
}

更简洁的Lambda风格写法(Spring Security 6+推荐)

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
    return http.csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/hello").permitAll()
                    .requestMatchers(HttpMethod.POST, "/hi").permitAll()
                    .requestMatchers("/authenticate").authenticated()
                    .anyRequest().authenticated())
            .formLogin(form -> form.permitAll())
            .logout(logout -> logout.permitAll())
            .build();
}

修改后重启应用,POST /hi即可正常免认证访问,/authenticate仍需认证,GET /hello保持原有正常访问逻辑。

内容的提问来源于stack exchange,提问作者B20DCCN483 - Nguyễn Đức Nhật

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:52:51