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

Spring Security中requestMatchers("/auth/**")配置导致/auth接口403的原因

问题原因分析

1. Controller路径映射配置错误

你在LoginController上使用的@RestController("/auth")写法存在误解:

  • @RestController注解的value参数是用来指定Bean的名称,而非请求路径前缀。
  • 当前你的@GetMapping未指定具体路径,因此该接口实际映射的是根路径/,而非你预期的/auth。

2. Spring Security规则匹配逻辑

  • 当配置.requestMatchers("/auth/**").permitAll();时,只有以/auth开头的请求(如/auth、/auth/xxx)会被允许访问。但你的接口实际映射到/,不在该规则覆盖范围内,因此被Spring Security拦截返回403。
  • 当改为.requestMatchers("/**").permitAll();时,所有请求路径(包括/)都被允许,因此可以正常调用接口。

修复方案

修改LoginController的注解配置,正确设置请求路径前缀:

@RestController
@RequestMapping("/auth") // 用该注解指定请求路径前缀
public class LoginController {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 此时该方法会映射到 /auth 路径
    @GetMapping
    public String showUserString(@RequestBody User user) {
        return "Hello World!";
    }
}

调整后,接口会正确映射到/auth路径,Spring Security的/auth/**规则也会匹配该请求,即可正常访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:52:43