Spring Security配置antMatchers放行接口不生效,返回forbidden错误
问题原因
你配置的antMatchers("/authenticate").permitAll()仅能让该接口跳过Spring Security原生的授权校验流程,但你手动添加的JwtRequestFilter属于全局过滤器,不会被该规则跳过,该过滤器默认会对所有请求执行Token校验逻辑,若/authenticate请求没有携带有效Token,就会触发认证失败返回403。除此之外还有路径不匹配、跨域预检请求未放行等可能原因。
解决方案
- 第一步:修改自定义JWT过滤器,跳过登录接口校验
在JwtRequestFilter的doFilterInternal方法最开头新增路径判断逻辑,匹配到/authenticate接口直接放行,不执行后续Token校验:
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 跳过登录接口校验 String requestUri = request.getRequestURI(); if ("/authenticate".equals(requestUri)) { filterChain.doFilter(request, response); return; } // 原有Token校验逻辑保持不变 // ... }
- 第二步:调整Security配置,放行跨域预检请求
前后端分离场景下浏览器会先发送OPTIONS类型的预检请求,这类请求不会携带Token,需要额外放行,可调整配置如下:
@Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() .authorizeRequests() // 放行所有OPTIONS预检请求 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行登录接口 .antMatchers("/authenticate").permitAll() // 其余请求需要认证 .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint) .and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); }
- 第三步:校验路径匹配规则
如果项目配置了server.servlet.context-path(例如配置为/api),那么接口实际访问路径为/api/authenticate,需要将配置中的antMatchers("/authenticate")调整为antMatchers("/api/authenticate"),确保路径匹配正确。
内容的提问来源于stack exchange,提问作者Sayed Hussainullah Sadat
相关产品推荐
相关产品推荐

