swagger 全局token设置
程序员文章站
2022-03-16 16:30:21
...
Swagger是一个很方便的东东,但正常使用时,我们的接口需要登陆才能访问的。即登陆时,要传一个登陆后的token才能访问的。
那这个怎么设置,才可以让所有接口都允许登陆后访问呢。
解决办法如下:
@EnableSwagger2
@Configuration
public class SwggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.forCodeGeneration(true)
.select()
// 扫描的路径包
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/")
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("datamonitor")
.description("datamonitor")
.version("1.0.0")
.build();
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList= new ArrayList();
apiKeyList.add(new ApiKey("x-auth-token", "x-auth-token", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts=new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build());
return securityContexts;
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences=new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
}
在swagger顶部会有一个Authorize 的按钮
点击后弹出窗口
在value中输入token 点击 Authorize 按钮就可访问Swagger中的接口