Swagger2不被SpringSecurity框架拦截的配置方法是什么
Swagger2不被SpringSecurity框架拦截的配置
打算在SpringSecurity框架中集成Swagger2框架进行接口功能的运行及测试,发现Swagger2会被SpringSecurity框架拦截,导致我们在浏览器中访问不了Swagger2首页。
解决这个问题的主要方法只需要在SpringSecurity的配置类中添加一个方法即可,博主的SpringSecurity的配置类定义为SecurityConfig,添加以下代码重启项目再访问即可;
/*
* 解决Security访问Swagger2被拦截的问题;
* */
@Override
public void configure(WebSecurity web) throws Exception {
// allow Swagger URL to be accessed without authentication
web.ignoring().antMatchers(
"/swagger-ui.html",
"/v2/api-docs", // swagger api json
"/swagger-resources/configuration/ui", // 用来获取支持的动作
"/swagger-resources", // 用来获取api-docs的URI
"/swagger-resources/configuration/security", // 安全选项
"/swagger-resources/**",
//补充路径,近期在搭建swagger接口文档时,通过浏览器控制台发现该/webjars路径下的文件被拦截,故加上此过滤条件即可。(2020-10-23)
"/webjars/**"
);
}Spring security5 集成swagger2无法访问
主要还是spring security把 swagger需要访问的URL被拦截,不只是swagger-ui.html这个URL
查找网上的解决方案没一个好用的,然后自己在跳转重定向的方法里打印了引发跳转的URL,一个一个试出来的老铁。累啊~
话不多说,放图,配置security配置类即可

成功:

完整配置类代码:
package com.lw.bpczy.security.config;
import com.lw.bpczy.security.authentication.MyAuthenticationFailureHandler;
import com.lw.bpczy.security.authentication.MyAuthenticationSuccessHandler;
import com.lw.bpczy.security.authorization.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsUtils;
/**
* @author: Liang Shan
* @date: 2019-11-12 10:25
* @description: security安全配置
* WebSecurityConfigurerAdapter提供简洁的方式来创建webSecurityConfigurer
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSuccessHandler successHandler;
@Autowired
private MyAuthenticationFailureHandler failureHandler;
@Autowired
private MyAccessDeniedHandler accessDeniedHandler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/*配置安全项*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/needLogin")
.loginProcessingUrl("/login").permitAll()
.successHandler(successHandler)
.failureHandler(failureHandler)
.and()
.authorizeRequests()
// 授权不需要登录权限的URL
.antMatchers("/needLogin",
"/swagger*//**",
"/v2/api-docs",
"/webjars*//**").permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().access("@rbacService.hasPermission(request,authentication)").
and().exceptionHandling().accessDeniedHandler(accessDeniedHandler).
and().cors().and().csrf().disable()
;
}
}