我正在开发一个RESTAPI服务。所有api请求都必须经过身份验证(用户由jwt令牌授权)。但我想让 swagger 的用户界面忽略这个规则
以下是我的配置:
@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
. 我做错了什么?
暂无答案!
目前还没有任何答案,快来回答吧!