这里使用spring boot 2.1.8
一、引入maven依赖
<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>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
二、配置类
@Configuration
@EnableSwagger2
//@EnableSwaggerBootstrapUI
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// .pathMapping("/")
.select()
// 指定当前包路径,这里就添加了两个包,注意方法变成了basePackage,中间加上成员变量splitor
.apis(RequestHandlerSelectors.basePackage("com.example.lwp.swagger2.swagger2authdemo.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
;
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("9.0")
.contact(new Contact("张三", "blog.csdn.net", "zhangsan@gmail.com"))
.contact(new Contact("李四", "blog.csdn.net", "zhangsan@gmail.com"))
// .license("The Apache License")
// .licenseUrl("http://www.baidu.com")
.build();
}
/**
* SecurityScheme 子类 BasicAuth OAuth ApiKey
* @return
*/
private List<SecurityScheme> securitySchemes(){
List<SecurityScheme> list = new ArrayList<>();
// basicAuth SwaggerBootstrapUI支持的不好,使用swagger原生UI
list.add(new BasicAuth("basicAuth"));
return list;
}
}
三、controller
authorizations = {@Authorization(value=“basicAuth”)}
@RestController
@RequestMapping("/auth")
@Api(tags = {"auth模块"}, description = "需要鉴权的模块(描述)") //
public class AuthController {
@GetMapping("/hello")
@ApiOperation("hello入口")
public String hello(String username){
return "hello " + username;
}
@GetMapping("/hello1")
@ApiOperation(value = "auth hello1接口", authorizations = {@Authorization(value="basicAuth")})
public String hello1(String username){
return "hello1 " + username;
}
...
四、swagger-ui
1.swagger-ui中显示有锁标志
2. 点击Authrize按钮
3.弹出验证表单,将内容填写,这里用户名密码使用 admin/123
4.输入成功关闭
5.查看对应接口显示已经使用basicAuth
6.测试接口,报文中显示
curl -X GET "http://localhost:8080/auth/hello1?username=13" -H "accept: */*" -H "authorization: Basic YWRtaW46MTIz"