Spring Security 3.1.0免认证端点配置异常及2.x代码迁移咨询
Spring Security 3.1.0 匿名访问配置问题及2.x迁移方案
当前代码登录弹窗问题解决
你遇到的浏览器弹出登录窗口的核心原因是禁用了匿名认证:.anonymous(a -> a.disable())。permitAll()的设计是允许匿名用户访问指定路径,但禁用匿名认证后,Spring Security会判定所有请求都必须经过认证,哪怕配置了permitAll的路径也不例外,因此触发了HTTP Basic的登录流程。
修复后的3.1.0代码如下(同时对齐你2.x版本中仅允许GET方法访问的需求):
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.http.HttpMethod; @Bean public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception { http .authorizeHttpRequests((requests) -> requests .requestMatchers(HttpMethod.GET, "/login", "/home").permitAll() .anyRequest().authenticated() ) .httpBasic(withDefaults()); return http.build(); }
2.x到3.1.0的迁移要点
- 抛弃
WebSecurityConfigurerAdapter:3.x版本已弃用该适配器,改为通过定义SecurityFilterChainBean来配置安全规则。 - API替换:
- 将
authorizeRequests()替换为authorizeHttpRequests() - 将
antMatchers()替换为requestMatchers(),如需限制请求方法,直接在参数中指定(如HttpMethod.GET)
- 将
- 移除父类配置调用:无需再调用
super.configure(http),基于Bean的配置不存在默认配置继承。 - 匿名认证默认启用:默认情况下匿名认证是开启的,除非有特殊业务需求,不要禁用,否则会导致
permitAll规则失效。
额外排查点
如果问题仍然存在,可检查:
- 请求路径是否与配置完全匹配(是否包含上下文路径、斜杠是否一致等)
- 是否有其他自定义过滤器或配置干扰了认证流程
内容的提问来源于stack exchange,提问作者Spongi
相关产品推荐
相关产品推荐

