Springboot整合swagger,以及开启环境、账号权限验证访问
一、配置swagger
pom.xml:
<!-- swagger -->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
config:
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI//加密码 -可自选
@Profile({"dev","test"})//测试环境可访问 -可自选
public class Swagger2Config {
/**
* 设置swagger跨域,提供给service调用
* @return
*/
@Bean
public WebMvcConfigurer crossConfigurer(){
WebMvcConfigurer webMvcConfigurerAdapter = new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/v2/api-docs");
registry.addMapping("/**");
}
};
return webMvcConfigurerAdapter;
}
@Bean
public Docket createRestApi(){
ParameterBuilder parameterBuilder = new ParameterBuilder();
parameterBuilder.name("x-access-token").description("令牌")
.name("languageCode").description("语言")
.name("Authorization").description("token令牌")
.modelRef(new ModelRef("string")).parameterType("header").required(false).build();
ArrayList<Parameter> objects = new ArrayList<>();
objects.add(parameterBuilder.build());
return new Docket(DocumentationType.SWAGGER_2)
.select()
//基础扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(objects)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("java")
.description("java项目打包成docker images并运行")
.version("1.0.0")
.build();
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 1允许任何域名使用
corsConfiguration.addAllowedOrigin("*");
// 2允许任何头
corsConfiguration.addAllowedHeader("*");
// 3允许任何方法(post、get等)
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
不要忘记修改基础扫描包路径
apis(RequestHandlerSelectors.basePackage("自己路径"))
当我们使用swagger,进行接口测试,担心暴露接口不安全时:
二、使用步骤
1.环境权限配置
Swagger2Config 中添加注解
对swagger文档配置只在测试环境可访问,生产环境不可访问。:
@Profile({"dev","test"})
2.账户权限配置
配置yml文件
在1.9.0版本时,针对Swagger的资源接口,SwaggerBootstrapUi提供了简单的Basic认证功能。
swagger:
production: false
basic:
enable: true
username: admin
password: 123456