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
相关产品推荐
相关产品推荐

