如何让 Swagger 绕过 WebSecurityConfig?
Posted
技术标签:
【中文标题】如何让 Swagger 绕过 WebSecurityConfig?【英文标题】:How to allow Swagger to bypass WebSecurityConfig? 【发布时间】:2020-02-10 03:31:27 【问题描述】:我有这样的基本配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
protected void configure(HttpSecurity httpSecurity) throws Exception
// We don't need CSRF for this example
httpSecurity.csrf().disable()
// dont authenticate this particular request
.authorizeRequests().antMatchers("/authenticate").permitAll().
// all other requests need to be authenticated
anyRequest().authenticated().and().
// make sure we use stateless session; session won't be used to
// store user's state.
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
所以基本上它允许 /authenticate 通过,但其他一切都需要令牌。我如何让它也绕过 Swagger?这使得开发变得困难,因为团队依赖 Swagger 来查看 API 文档。
【问题讨论】:
【参考方案1】:在 antMatchers 中使用 permitAll().
添加 swagger 端点,或者您可以使用 configure(WebSecurity WebSecurity) 并使用 .ignoring()
参见 here
protected void configure(HttpSecurity httpSecurity) throws Exception
httpSecurity.csrf().disable()
.authorizeRequests()
.antMatchers("/authenticate").permitAll()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**").permitAll()
.anyRequest().authenticated().and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
【讨论】:
以上是关于如何让 Swagger 绕过 WebSecurityConfig?的主要内容,如果未能解决你的问题,请参考以下文章
如何让 Swagger 在生成的 HTML(在 Swagger UI 页面中)中添加新行?
064Spring Boot如何让Web API自动生成文档,并解决swagger-annotations的API注解description属性废弃的问题