Swagger:配置记录

917 阅读2分钟

带Header安全验证方式的

1. OAS_30方式

默认访问方式:http://localhost:8080/swagger-ui/index.html

1.1 pom依赖

    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-boot-starter</artifactId>
      <version>${springfox.verion}</version>
    </dependency>

1.2 resources

application.yml

spring:
  swagger:
    front:
      groupName: 前台管理
      basePackage: com.ecommerce.onion.application
      title: 订单管理AI
      description: 采用领域驱动开发方式,处理订单的过程(安全验证)
      contactName: luds
      contactUrl: https://juejin.cn/user/4327332666152279
      contactEmail: 
      version: 1.0.0
      enable: true
    back:
      groupName: 后台管理
      basePackage: com.ecommerce.onion.application
      title: 订单管理API
      description: 采用领域驱动开发方式,处理订单的过程
      contactName: luds
      contactUrl: https://juejin.cn/user/4327332666152279
      contactEmail: 
      version: 1.0.0
      enable: true

1.3 SwaggerProperties.java

/**
 * swagger的属性配置类
 */
@ConfigurationProperties(prefix = "spring.swagger")
@Data
public class SwaggerProperties {
	/**
	 * 前台接口配置
	 */
	private SwaggerEntity front;
	/**
	 * 后台接口配置
	 */
	private SwaggerEntity back;
	@Data
	public static class SwaggerEntity {
		private String groupName;
		private String basePackage;
		private String title;
		private String description;
		private String contactName;
		private String contactEmail;
		private String contactUrl;
		private String version;
		private Boolean enable;
	}
}

1.4 SwaggerConfig.java

@EnableOpenApi
@Configuration
@EnableConfigurationProperties(value = {SwaggerProperties.class})
public class SwaggerConfig {
	/**
	 * 配置属性
	 */
	@Autowired
	private SwaggerProperties properties;
	@Bean
	public Docket frontApi() {
		RequestParameter parameter = new RequestParameterBuilder()
				.name("platform")
				.description("请求头")
				.in(ParameterType.HEADER)
				.required(true)
				.build();
		List<RequestParameter> parameters = Collections.singletonList(parameter);
		return new Docket(DocumentationType.OAS_30)
				//是否开启,根据环境配置
				.enable(properties.getFront().getEnable())
				.groupName(properties.getFront().getGroupName())
				.apiInfo(frontApiInfo())
				.select()
				//指定扫描的包
				.apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))
				.paths(PathSelectors.any())
				.build()
				.securitySchemes(securitySchemes())
				.securityContexts(securityContexts());
	}
	/**
	 * 设置授权信息
	 */
	private List<SecurityScheme> securitySchemes() {
		ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
		return Collections.singletonList(apiKey);
	}
	/**
	 * 授权信息全局应用
	 */
	private List<SecurityContext> securityContexts() {
		return Collections.singletonList(
				SecurityContext.builder()
						.securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
						.build()
		);
	}
	/**
	 * 前台API信息
	 */
	private ApiInfo frontApiInfo() {
		return new ApiInfoBuilder()
				.title(properties.getFront().getTitle())
				.description(properties.getFront().getDescription())
				.version(properties.getFront().getVersion())
				.contact(    //添加开发者的一些信息
						new Contact(properties.getFront().getContactName(), properties.getFront().getContactUrl(),
								properties.getFront().getContactEmail()))
				.build();
	}

	/**
	 * 后台API
	 */
	@Bean
	public Docket backApi() {
		return new Docket(DocumentationType.OAS_30)
				//是否开启,根据环境配置
				.enable(properties.getBack().getEnable())
				.groupName("后台管理")
				.apiInfo(backApiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage(properties.getBack().getBasePackage()))
				.paths(PathSelectors.any())
				.build();
	}

	/**
	 * 后台API信息
	 */
	private ApiInfo backApiInfo() {
		return new ApiInfoBuilder()
				.title(properties.getBack().getTitle())
				.description(properties.getBack().getDescription())
				.version(properties.getBack().getVersion())
				.contact(    //添加开发者的一些信息
						new Contact(properties.getBack().getContactName(), properties.getBack().getContactUrl(),
								properties.getBack().getContactEmail()))
				.build();
	}

}

2. Swagger2方式(老版本)

默认访问方式:http://localhost:8080/swagger-ui/index.html

或者 http://localhost:8080/doc.html#

2.1 pom依赖

    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>1.9.6</version>
    </dependency>

2.2 SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .securityContexts(Arrays.asList(securityContext()))
                    .securitySchemes(Arrays.asList(apiKey(),apiKeyUserName()))
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.ecommerce.onion.application"))
                    .paths(PathSelectors.any())
                    .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                   .title("title")
                   .description("test")
                   .version("0.0.1")
                   .build();
    }
    private ApiKey apiKeyUserName(){
        return new ApiKey("userName","userName","header");
    }
    private ApiKey apiKey(){
        return new ApiKey("Authorization","Authorization","header");
    }
    private SecurityContext securityContext(){
        return SecurityContext.builder().securityReferences(defaultAuth()).build();
    }
    private List<SecurityReference> defaultAuth(){
        AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] =authorizationScope;
        return Arrays.asList(new SecurityReference("Authorization",authorizationScopes),new SecurityReference("userName",authorizationScopes));
    }
}

3. 遇到上线环境禁用Swagger这种需求,该如何处理,看一下不同结果

3.1 对话框样式Swagger2

  • @Profile({"dev","test"})
  • @ConditionalOnProperty(prefix = "swagger2", value = {"enable"}, havingValue = "true")

image.png

注意:后台,会有报错信息

3.2 错误页

  • Docket(DocumentationType.OAS_30).enable(false)

image.png

注意:后台,平静如水,没报错误信息