首页 > 解决方案 > 如何让 Swagger-UI 忽略安全过滤器

问题描述

我正在开发一个REST API服务。所有 API 请求都必须经过身份验证(用户由 JWT 令牌授权)。但我想让swagger-ui忽略这条规则

这是我的配置:

@Configuration
    public static class JwtConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        JwtTokenProvider jwtTokenProvider;
        
        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                .ignoring()
                .antMatchers("/swagger-ui/**");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .antMatcher("/api/**").cors()
            .and()
            .csrf().disable()
            .authorizeRequests().antMatchers("/api/**").authenticated()
            .and()
            .apply(new JwtConfigurer(jwtTokenProvider));
        }
    
}

public class JwtConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private JwtTokenProvider jwtTokenProvider;
    
    public JwtConfigurer(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider);
        http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

public class JwtTokenFilter extends GenericFilterBean {
    private JwtTokenProvider jwtTokenProvider;
    
    public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
                throws IOException, ServletException {
            String token = jwtTokenProvider.resolveToken((HttpServletRequest) req);
    
            if (token != null && jwtTokenProvider.validateToken(token)) {
                Optional<Authentication> authentication = jwtTokenProvider.getAuthentication(token);
                if(authentication.isPresent()) {
                    SecurityContextHolder.getContext().setAuthentication(authentication.get());
                    filterChain.doFilter(req, res);
                } else {
                    responseForbidden(res);
                }
            } else {
                responseForbidden(res);
            }
      }

      private void responseForbidden(ServletResponse res) throws IOException {
            ((HttpServletResponse) res).sendError(HttpServletResponse.SC_FORBIDDEN, "The token is not valid.");
      }
}

现在所有请求都由JwtConfigurer. 我究竟做错了什么?

标签: javaspring-bootspring-securityjwt

解决方案


推荐阅读