【发布时间】:2017-08-22 13:13:28
【问题描述】:
我在 spring 应用中有 springfox-swagger2(2.6.1 版)和 springfox-swagger-ui(2.6.1 版)。
如何为需要继续授权的调用配置授权令牌(如何为 swagger 设置 X-AUTH-TOKEN)。
谢谢!
【问题讨论】:
标签: spring swagger swagger-ui swagger-2.0 springfox
我在 spring 应用中有 springfox-swagger2(2.6.1 版)和 springfox-swagger-ui(2.6.1 版)。
如何为需要继续授权的调用配置授权令牌(如何为 swagger 设置 X-AUTH-TOKEN)。
谢谢!
【问题讨论】:
标签: spring swagger swagger-ui swagger-2.0 springfox
X-AUTH-TOKEN 的标题。我们使用密钥mykey 引用此方案。private ApiKey apiKey() {
return new ApiKey("mykey", "X-AUTH-TOKEN", "header");
}
/anyPath/customers,我们可能需要accessEverything 的范围。private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*"))
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(
new SecurityReference("myKey", authorizationScopes));
}
然后在您的案卷中关联新创建的安全上下文和安全方案。
new Docket(...)
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
现在要启用 swagger UI,您需要提供以下 bean 配置
@Bean
SecurityConfiguration security() {
return new SecurityConfiguration(
"test-app-client-id",
"test-app-client-secret",
"test-app-realm",
"test-app",
"YOUR_API_AUTH_TOKEN",
ApiKeyVehicle.HEADER,
"X-AUTH-TOKEN",
"," /*scope separator*/);
}
这告诉 swagger-ui 您将使用 api 密钥并在构建时提供 api 身份验证令牌(可能使用加密的配置属性。
注意:swagger-ui 的可配置性有限。它服务于 80% 的用例。额外的自定义可能意味着您将无法使用捆绑的 swagger-ui。
【讨论】: