Swagger token认证,一次配置多次生效
swagger 给开发人员调试接口带来了很大的方便,但是当调试接口的时候,如果需要校验 token (此处叫Authorize),会很麻烦,每次访问接口都需要输入一次 token去认证,在此提供一次配置多次生效的解决方案。
1、在SwaggerConfig.java中配置,重启后端项目后,在swagger页面的右上角会出现一个 Authorize 按钮
(1)在securitySchemes的ApiKey中增加一个名名称为“Authorization”,类型为“header”的参数
private List<ApiKey> securitySchemes() {
return newArrayList( new ApiKey("Authorization", "Authorization", "header"));
}
(2)在securityContexts中添加你要 一次配置多次生效 的接口名称,forPaths() 中放入要生效的接口路径的正则表达式,如 .forPaths(PathSelectors.regex("^(?!menus).*$")) 表示所有带有 menus 的接口路径。此处,使用 PathSelectors.any() 表示所有接口路径都生效
private List<SecurityContext> securityContexts() {
return newArrayList( SecurityContext.builder() .securityReferences(defaultAuth())
// .forPaths(PathSelectors.regex("^(?!menus).*$"))
.forPaths(PathSelectors.any())
.build() );
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList( new SecurityReference("Authorization", authorizationScopes));
}
(3)在createRestApi 中加入以上两步配置的 securitySchemes 和 securityContexts
return new Docket(DocumentationType.SWAGGER_2).
useDefaultResponseMessages(false) .select() .
apis(RequestHandlerSelectors.any()) .
paths(PathSelectors.regex("^(?!auth).*$")) .
build() .
securitySchemes(securitySchemes()) .
securityContexts(securityContexts()) ;
}
2、点击Authorize ,输入Authorize 值

(1)找到任意接口的 Authorization 值,我的方法是 打开F12,任意访问一个接口,在 NetWork 中的header信息找到Authorization 值

(2)在Authorize弹框的 value 输入框中输入刚刚获取的 Authorize 值,然后点击 Authorize 使用该 Authorize 值。接下来我们访问接口就无需理会 要输入的 Authorize 值了
