Spring Boot Security中如何避免Swagger路径被自定义过滤器拦截
问题原因
你当前配置不生效的核心原因有两点:
WebSecurity.ignoring()配置的路径匹配规则错误、覆盖不全:你写的/api-docs/仅能匹配完全相等的路径,无法匹配接口文档子路径、静态资源路径,且主流OpenAPI 3的接口文档路径前缀为/v3/api-docs,你配置的路径少了版本前缀和通配符。- 被
@Component注解修饰的OncePerRequestFilter会被Spring Boot自动注册到全局Servlet过滤器链,哪怕是配置了web.ignoring()的路径也会触发该过滤器。
解决方案
按以下两步修改即可:
第一步:修正WebSecurity忽略路径配置
把所有Swagger/OpenAPI相关路径都加入忽略列表:
@Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers( "/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**", "/webjars/**", "/favicon.ico" ); }
如果是Swagger2版本,额外添加"/v2/api-docs/**"到列表即可。
第二步:二选一配置过滤器跳过逻辑
方案1:重写过滤器的跳过规则
修改SampleTokenFilter,新增路径匹配逻辑,匹配到Swagger相关路径直接跳过鉴权:
@Component public class SampleTokenFilter extends OncePerRequestFilter { // 待跳过的路径列表 private static final String[] SKIP_PATHS = new String[]{ "/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**", "/webjars/**", "/favicon.ico" }; private final AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { // 路径匹配成功则跳过当前过滤器 for (String path : SKIP_PATHS) { if (antPathMatcher.match(path, request.getRequestURI())) { return true; } } return super.shouldNotFilter(request); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 保持原有鉴权逻辑不变 } }
方案2:调整过滤器注册方式
去掉SampleTokenFilter上的@Component注解,避免被Spring Boot自动注册到全局过滤器链,仅在Spring Security的过滤器链中手动注册,这样web.ignoring()的路径自然不会触发该过滤器:
// 去掉类上的@Component注解 public class SampleTokenFilter extends OncePerRequestFilter { // 原有doFilterInternal逻辑保持不变 } // 在Security配置类中手动注册过滤器 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SeqConfiguration extends WebSecurityConfigurerAdapter { // 手动实例化过滤器 @Bean public SampleTokenFilter sampleTokenFilter() { return new SampleTokenFilter(); } // 原有其他配置保持不变 }
内容的提问来源于stack exchange,提问作者Satscreate
相关产品推荐
相关产品推荐

