Swagger权限控制
- Swagger2登录安全控制
- Swagger2 BasicAuth身份认证
- Swagger2 ApiKey身份认证
Swagger2登录安全控制
- 需要在appliction.properties中添加如下语句:
swagger.basic.enable=true
swagger.basic.username=username
swagger.basic.password=123456
swagger.production=false
swagger2.enabled=true
- 在swagger类中开启如下注解:
@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2
//@EnableSwaggerBootstrapUI
@Profile({"dev", "test", "pre", "prod"})
public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter {
@Value("${swagger2.enable}")
private boolean swagger2Enable;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swagger2Enable)
// 绑定swagger-ui的展示内容
.apiInfo(apiInfo())
.select()
// 绑定扫描的类
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.build()
.enable(swagger2Enable)
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/**
* 指定swagger2 ui的显示格式
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger和springBoot整合演示")
.description("swagger的API文档演示效果")
.version("1.0")
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
}
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> list = new ArrayList<>();
list.add(new BasicAuth("basicAuth"));
list.add(new ApiKey("write_token","write_token","header"));
list.add(new ApiKey("read_token","read_token","query"));
return list;
}
private List<SecurityContext> securityContexts() {
return Arrays.asList(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build()
);
}
}
- 展示效果
Swagger2 BasicAuth身份认证
Swagger2 ApiKey身份认证
实例演示
package com.example.springbootswagger2.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.example.springbootswagger2.model.Student;
@Api(value = "Swagger2RestController",
description = "学生服务")
@RestController
public class Swagger2RestController {
/**
* 组合所有的学生信息
*/
List<Student> students = new ArrayList<Student>();
{
students.add(new Student("Sajal", "IV", "India"));
students.add(new Student("Lokesh", "V", "India"));
students.add(new Student("Kajal", "III", "USA"));
students.add(new Student("Sukesh", "VI", "USA"));
}
/**
*
* @return
*/
@ApiOperation(value = "以列表形式返回学生信息",
responseContainer="List",
response = Student.class,
tags = "getStudents",
authorizations={@Authorization(value="basicAuth")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/getStudents", method = RequestMethod.GET)
public List<Student> getStudents() {
return students;
}
/**
*
* @param name
* @return
*/
@ApiOperation(value = "获取指定名字的学生",
response = Student.class,
tags = "getStudentByName",
authorizations={@Authorization(value="read_token")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/getStudent/{studentName}", method = RequestMethod.GET)
public Student getStudentByName(@RequestParam @ApiParam(value = "studentName") String name) {
return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);
}
/**
*
* @param country
* @return
*/
@ApiOperation(value = "获取指定国家的学生",
responseContainer="List",
response = Student.class,
tags = "getStudentByCountry",
authorizations={@Authorization(value="read_token")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/getStudentByCountry/{country}", method = RequestMethod.GET)
public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
System.out.println("Searching Student in country : " + country);
List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
.collect(Collectors.toList());
System.out.println(studentsByCountry);
return studentsByCountry;
}
/**
*
* @param cls
* @return
*/
@ApiOperation(value = "获取指定班级的学生",
responseContainer="List",
response = Student.class,
tags="getStudentByClass",
authorizations={@Authorization(value="read_token")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/getStudentByClass/{cls}", method = RequestMethod.GET)
public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
}
@ApiOperation(value = "添加学生",
tags="addStudent",
authorizations={@Authorization(value="write_token")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/addStudent", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"})
public Boolean addStudent(@ApiParam(value = "student") @RequestBody Student student) {
return students.add(student);
}
@ApiOperation(value = "添加学生V2",
tags="addStudentV2",
authorizations={@Authorization(value="write_token")})
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "姓名", paramType = "query"),
@ApiImplicitParam(name = "cls", value = "班级", paramType = "query"),
@ApiImplicitParam(name = "country", value = "国家", paramType = "query")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "/addStudentV2", method = RequestMethod.GET)
public Boolean addStudentV2(@RequestParam String name,
@RequestParam String cls,
@RequestParam String country) {
Student student = new Student(name, cls, country);
return students.add(student);
}
@ApiOperation(value = "查找指定班级指定名字的学生", tags = "getStudentByNameAndCls",
authorizations={@Authorization(value="read_token")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "getStudentByNameAndCls", method = RequestMethod.GET)
public Student getStudentByNameAndCls(@RequestParam String name, @RequestParam String cls) {
return students.stream()
.filter(x -> x.getCls().equals(cls) && x.getName().equalsIgnoreCase(name))
.collect(Collectors.toList()).get(0);
}
@ApiOperation(value = "删除指定名字的学生", tags = "delStudentByName",
authorizations={@Authorization(value="basicAuth")})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Suceess|OK"),
@ApiResponse(code = 401, message = "not authorized!"),
@ApiResponse(code = 403, message = "forbidden!!!"),
@ApiResponse(code = 404, message = "not found!!!") })
@RequestMapping(value = "delStudentByName", method = RequestMethod.GET)
public Student delStudentByName(@RequestParam String name) {
Student tempStudent = null;
for (Student student : students) {
if (student.getName().equalsIgnoreCase(name)) {
tempStudent = student;
break;
}
}
students.remove(tempStudent);
return tempStudent;
}
}