BackGround-背景
Recently, I am coding a Spring Cloud project, that I need to test something with Swagger.The problem is that I need to route and filter the request urls of Swagger in case of being block by JWT Auth & Gateway Custom Filter.
最近,我在做一个微服务项目,需要用到Swagger。问题是我需要路由过滤请求,防止他被JWT和网关自定义过滤器给阻挡。
Project Structure 项目结构
There are 2 consumers modules and 1 gateway module in this project.
这有2个消费者 和1个生产者。
Process-过程
Add depencies of swagger2 & ui to commons module.Here I use version-2.9.2
- Add Maven dependencies of swagger2 & ui to commons module.Here I use version-2.9.2.
在commons模块添加swagger2和ui的Maven依赖,这里我使用的版本是-2.9.2.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- Create SwaggerConfig.java to admin & app-server modules.At the same time,don’t forget to add urls pattern of Swagger including its urls static urls to the interceptors to make it free to be visited without token as we make token interceptor for authorization.
在admin和app-server模块下添加SwaggerConfig.java配置类。与此同时,由于我们做了token认证的拦截器,别忘记把swagger的访问的路径,包括他的静态文件路径到拦截器里排除掉,使他们能够被正常访问。
package com.tanhua.admin.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: SwaggerCongig配置
* @Author: Spike Wong
* @Date: 2022/9/8
*/
@Slf4j
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private boolean SWAGGER_IS_ENABLE = true;
/**
* 创建文档接口信息
*
* @return
*/
public ApiInfo createApiInfo() {
return new ApiInfoBuilder()
.title("鸡你太美-交友Admin后端文档")
.description("陌生人交友")
.contact(new Contact("ikun探花交友论坛", "tanhua.com", "tanhua@tanhua.com"))
.version("1.0.0").build();
}
/**
* ioc 容器 存储bean
*
* @return
*/
@Bean
public Docket createApi() {
//加token的
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("token").description("token")
.modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.