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

Spring Security中.authenticated()未生效,指定接口无需认证即可访问

问题原因及解决方案

核心原因

Spring Security的权限规则是从上到下依次匹配,一旦匹配到第一个符合的规则就会终止后续判断。你的配置中:

.authorizeHttpRequests(authorize ->
        authorize.requestMatchers("/api/v1/auth/**")
                .permitAll()
                .requestMatchers("/api/v1/auth/login/**")
                .permitAll().anyRequest()
                .authenticated())

第一个规则/api/v1/auth/**已经覆盖了/api/v1/auth/login/create(**匹配任意层级路径),所以该接口直接应用permitAll()规则,完全不会触发anyRequest().authenticated()的校验。此外,你错误地将需要认证的/api/v1/auth/login/**也设置为permitAll(),这进一步加剧了问题。

修复方案

调整规则顺序,将需要认证的接口规则放在最前面,同时修正权限配置:

方案一:精准控制/login/**接口权限

.authorizeHttpRequests(authorize ->
        // 先匹配需要认证的/login/**接口
        authorize.requestMatchers("/api/v1/auth/login/**")
                .authenticated()
        // 再放开/auth下其他不需要认证的接口
        .requestMatchers("/api/v1/auth/**")
                .permitAll()
        // 最后要求所有其他接口必须认证
        .anyRequest()
                .authenticated())

方案二:更清晰的白名单模式(推荐)

明确列出不需要认证的/auth接口,避免用**过度匹配:

.authorizeHttpRequests(authorize ->
        // 仅放开不需要认证的接口,比如注册、验证码等
        authorize.requestMatchers("/api/v1/auth/register", "/api/v1/auth/send-code")
                .permitAll()
        // /auth下其他所有接口(包括login/create)要求认证
        .requestMatchers("/api/v1/auth/**")
                .authenticated()
        // 全局其他接口要求认证
        .anyRequest()
                .authenticated())

关键说明

  • 规则顺序至关重要:更具体的路径规则必须放在更宽泛的路径规则前面,否则宽泛规则会覆盖具体规则。
  • 确保目标接口的权限配置正确:将/api/v1/auth/login/**的权限从permitAll()改为authenticated(),符合你“登录后才可访问”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:46:12