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

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的迁移要点

  1. 抛弃WebSecurityConfigurerAdapter:3.x版本已弃用该适配器,改为通过定义SecurityFilterChain Bean来配置安全规则。
  2. API替换:
    • 将authorizeRequests()替换为authorizeHttpRequests()
    • 将antMatchers()替换为requestMatchers(),如需限制请求方法,直接在参数中指定(如HttpMethod.GET)
  3. 移除父类配置调用:无需再调用super.configure(http),基于Bean的配置不存在默认配置继承。
  4. 匿名认证默认启用:默认情况下匿名认证是开启的,除非有特殊业务需求,不要禁用,否则会导致permitAll规则失效。

额外排查点

如果问题仍然存在,可检查:

  • 请求路径是否与配置完全匹配(是否包含上下文路径、斜杠是否一致等)
  • 是否有其他自定义过滤器或配置干扰了认证流程

内容的提问来源于stack exchange,提问作者Spongi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:35:18