Swagger2不被SpringSecurity框架拦截的配置说明

3 篇文章 0 订阅
1 篇文章 0 订阅

       今天博主打算在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/**"
    					
    					
    			);
    }
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以通过在Spring Security配置中添加以下内容来放行Swagger2: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**") .permitAll() .anyRequest() .authenticated() .and() .csrf() .disable(); } } ``` 这个配置将允许访问Swagger UI和API文档,而不需要进行身份验证。 ### 回答2: Spring Security是一个灵活的框架,可以用于构建各种类型的安全的应用程序。它可以在应用程序中实现身份验证和授权,并确保Web应用程序的安全性。Swagger是一种API文档规范和工具,用于描述Web服务的结构和功能。Swagger为Web服务的用户提供交互式和完整的文档,因此在实现API的时候会用到SwaggerSpring Security默认情况下会保护应用程序中的所有URI。但是,有时候我们需要放行Swagger的相关路径,这时候我们需要对Spring Security进行配置。 首先,配置Swagger的相关依赖项。在pom.xml中添加以下依赖: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.5.2</version> </dependency> ``` 接下来,需要在Spring Security中启用跨域资源共享(CORS)。CORS必须启用,否则将无法通过Swagger UI访问REST API。在WebSecurityConfigurerAdapter类中重写configure(HttpSecurity http)方法并添加以下代码: ```java http.cors().and().csrf().disable(); ``` 还需要更新Swagger的默认配置,以包括与Spring Security的整合。我们可以在AppConfig类中添加以下配置: ```java @Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList(apiKey())) .securityContexts(Arrays.asList(securityContext())); } private ApiKey apiKey() { return new ApiKey("JWT", AUTHORIZATION_HEADER, "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.any()) .build(); } List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Arrays.asList(new SecurityReference("JWT", authorizationScopes)); } } ``` 这里,我们将API文档令牌设置为JWT并将其添加到默认的安全上下文中。接下来,我们可以将匹配所有Swagger UI路径的请求放行,以允许用户在UI中访问API文档。在WebSecurityConfigurerAdapter类中添加以下配置: ```java @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**"); } ``` 以上代码将Spring Security配置为忽略Swagger的所有路径。这样后,Swagger UI就可以在应用程序中使用了。 总之,要放行Swagger2,首先需要在pom.xml中添加Swagger相关依赖项,然后在Spring Security中启用CORS,更新Swagger的默认配置并将所有Swagger UI路径请求放行。这样就可以在应用程序中使用Swagger UI了。 ### 回答3: 在使用Spring Security进行权限控制的时候,我们可能需要对某些页面或者接口进行放行,以便于开发人员或者测试人员进行访问。在这种情况下,我们需要对Spring Security进行相应的配置,使得它能够对一些特定的URL进行放行。在此,我们可以以Swagger2为例,介绍一下如何进行配置。 首先,我们需要在Spring Boot配置文件中进行一些基本的配置,以便于让Swagger2正常运行。我们可以在pom.xml文件中加入如下依赖: ``` <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.3.RELEASE</version> </dependency> ``` 然后,在Spring Boot配置文件中加入如下配置: ``` swagger.enabled=true #启用swagger swagger.basePackage=com.example.swaggerdemo.controller #扫描的接口所在的包 swagger.title=swagger demo #文档标题 swagger.description=swagger demo API #文档描述 swagger.version=1.0.0 #文档版本号 ``` 接下来,我们需要配置Spring Security,使得它能够对Swagger2进行放行。我们可以在WebSecurityConfigurerAdapter的子类中进行如下配置: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //放行Swagger2的接口 .antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/**", "/configuration/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .permitAll() .and() .logout() .permitAll(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/swagger-resources/**", "/webjars/**"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService); } } ``` 在这里,我们配置了对Swagger2的接口进行放行,使得它们可以被任何人正常访问。同时,我们还需要配置忽略Swagger2的一些资源文件,以避免出现权限问题。最后,我们还需要对Spring Security进行基本的认证授权配置,这些配置可以根据具体的业务需求进行相应的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值