swagger可以为前端提供接口文档及接口测试功能,后端集成起来很方便,对代码也没有入侵,全注解完成,非常好用。
一、集成基础功能
第一步、添加依赖
<!-- swagger3 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
第二步、创建配置文件Swagger3Config
@Configuration
@EnableOpenApi
public class Swagger3Config {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
// 自行修改为自己的接口路径,不配置扫描全部路径
.apis(RequestHandlerSelectors.basePackage("com.by.hellosecurityresource.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3 API文档")
.description("RESTFul 风格接口")
.version("1.0")
.build();
}
}
第三步、给接口添加注解
@Api(tags = "测试不需要登录验证就能访问的接口")
@RestController
@RequestMapping("/noAuth")
public class NoAuthController {
/**
* 服务对象
*/
private TestService testService;
public NoAuthController(TestService testService) {
this.testService = testService;
}
@Operation(summary = "获取test列表数据")
@RequestMapping(value = "", method = RequestMethod.GET)
public Page<STest> list(@RequestParam @Parameter(description = "页数从1开始", required = true) int page,
@RequestParam @Parameter(description = "每页的条数", required = true) int limit,
HttpServletRequest request) {
return testService.list(page - 1, limit);
}
}
Api 给Controller添加的注解
Operation 给Contoller里的方法添加的注解
Parameter 给方法中参数添加的注解
Schema 给实体类及其变量添加的注解
@Schema(description = "test数据")
@Setter
@Getter
public class TestRequestBean {
@Schema(description = "测试字段1")
private String test;
@Schema(description = "测试字段2")
private String value;
}
访问地址: baseUrl/swagger-ui/index.html
二、让swgger文档支持授权访问
修改配置文件,使swagger支持添加token
@Configuration
@EnableOpenApi
public class Swagger3Config {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
// 自行修改为自己的接口路径,不配置扫描全部路径
.apis(RequestHandlerSelectors.basePackage("com.by.hellosecurityresource.controller"))
.paths(PathSelectors.any())
.build()//;
.securitySchemes(securitySchemes())
.securityContexts(Collections.singletonList(securityContext()));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3 API文档")
.description("RESTFul 风格接口")
.version("1.0")
.build();
}
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> apiKeyList= new ArrayList<>();
//注意,这里应对应登录token鉴权对应的k-v
apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
return apiKeyList;
}
/**
* 这里设置 swagger2 认证的安全上下文
*/
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("Authorization", scopes())))
.build();
}
/**
* 这里是写允许认证的scope
*/
private AuthorizationScope[] scopes() {
return new AuthorizationScope[]{
new AuthorizationScope("web", "All scope is trusted!")
};
}
}
ResourseServer配置中,过滤以下路径,使不通过验证就能访问到,否则无法打开swagger文档
"/swagger-ui/**"
"/swagger-resources/**"
"/v3/**"
示例代码如下
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/noAuth/**", "/swagger-ui/**", "/swagger-resources/**", "/v3/**").permitAll() //设置/oauth/**的接口不需要授权就可以访问
.anyRequest().authenticated();
}
再次访问接口文档,会有此按钮标记
点击可输入token
这样,在swagger中测试接口的时候就会带上token了。
三、生产服务器注意关闭swagger文档
在applicaiton中添加配置
springfox:
documentation:
auto-startup: false #false关闭swagger文档 true打开swagger
测试代码地址:
Hello-Security: OAuth2授权服务器