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

Spring Security路由认证配置失效问题求助

问题分析与解决方案

核心原因:规则顺序与匿名认证特性

你观察到的anonymousUser且isAuthenticated()返回true确实和问题相关,但直接原因是请求授权规则的顺序错误。

在Spring Security中,匿名认证是默认行为:当请求没有有效认证信息时,框架会生成AnonymousAuthenticationToken,它的isAuthenticated()返回true——这只是表示该身份是框架认可的匿名身份,并非真正的已认证用户。而Spring Security的authenticated()规则会自动排除这种匿名身份,但你的规则顺序让permitAll()优先覆盖了认证要求:

你的配置里:

auth.requestMatchers("/api/v1/auth/register/**", "/api/v1/auth/login" , "/api/v1/profile/**").permitAll();
auth.requestMatchers("/api/v1/profile").authenticated();

/api/v1/profile/**的模糊匹配会命中/api/v1/profile(**匹配任意层级路径),所以permitAll()规则先生效,导致未认证用户也能访问该路径。另外你需求里的路径是/api/v1/auth/profile/**,但配置里写的是/api/v1/profile/**,这可能是笔误,进一步加剧了匹配错误。

修复步骤

  1. 调整规则顺序,修正路径书写
    把更具体的路径规则放在前面,模糊规则后置,同时修正路径与需求一致:

    .authorizeHttpRequests(auth -> {
        // 先放行无需认证的具体路径
        auth.requestMatchers("/api/v1/auth/register/**", "/api/v1/auth/login").permitAll();
        // 放行/auth/profile下的子路径
        auth.requestMatchers("/api/v1/auth/profile/**").permitAll();
        // 要求/auth/profile必须认证
        auth.requestMatchers("/api/v1/auth/profile").authenticated();
        // 其他所有请求都需要认证
        auth.anyRequest().authenticated();
    })
    

    这样/api/v1/auth/profile会优先匹配authenticated()规则,而子路径/api/v1/auth/profile/**会匹配permitAll(),完全符合你的需求。

  2. 代码中手动判断认证状态(可选)
    如果你需要在业务代码里区分真实认证用户和匿名用户,不要仅依赖isAuthenticated(),应该结合身份类型判断:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    boolean isRealAuthenticated = authentication != null 
        && authentication.isAuthenticated() 
        && !(authentication instanceof AnonymousAuthenticationToken);
    

额外说明

你的Redis Session存储、Session管理配置本身没有问题,问题完全出在授权规则的顺序和路径匹配上。调整后即可实现预期的权限控制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:31:05