java - 如何让 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
. 我究竟做错了什么?
解决方案
推荐阅读
- python - 读取 CSV 文件和打印每个用户的日期列表的代码
- android - 如何在 YoutubePlayerView android 中启用右键单击事件和左键单击事件
- svelte - 将 Svelte 生成的节点注入静态 DOM
- javascript - 如何从名为 George 的对象中获取价值
- python - 为什么我的正则表达式有一个奇怪的行为?这是一个错误吗?
- python - 在分页的情况下,用于fundtion的烧瓶网址不起作用
- linux-kernel - 如何在 ubuntu 上为 qemu 和 kvm 设置 Beaglebone black?
- laravel - 无法在 laravel-6 中上传图片,显示错误:“E:\xampp\tmp\php3A05.tmp”文件不存在或不可读
- c++ - 如何复制只有两个迭代器的数据?
- javascript - 无法扩展来自其他包的抽象类