我正在使用带有角度2前端的弹簧靴,我想为我的招摇配置添加授权。
我目前的springfox设置如下:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("mybasepackage"))
.paths(PathSelectors.ant("/api/*"))
.build();
}
}
我的应用程序使用JWT过滤器进行授权,我希望swagger只要在用户浏览器中没有过期就使用该标记。
我看到我可以像这样添加HTML文件:
function addApiKeyAuthorization() {
var key = JSON.parse(localStorage.getItem("ls.authentication-token"));
if (key && key.trim() != "") {
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header");
window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth);
log("Set bearer token: " + key);
}
}
因为我使用的是Springfox,所以我没有这个选项。有没有办法可以通过Docket api添加它?
答案 0 :(得分:2)
为了将JWT令牌添加到Authorization标头,在SwaggerConfig
类中添加以下bean:
@Bean
public SecurityConfiguration security() {
return new SecurityConfiguration(null, // "client id",
null, // "client secret",
null, // "realm",
null, // "app",
"Bearer " + yourToken, ApiKeyVehicle.HEADER, "Authorization", "," /* scope separator */);
}
答案 1 :(得分:2)
I had two dependencies, springfox-swagger2 and springfox-swagger-ui. I ended up removing the springfox-swagger-ui dependency.
Jhipster used an example where they make Get calls to the packaged swagger files from springfox-swagger2. I was able to use this example with a few small changes.
I added the swagger-ui configuration to my public folder. Since I am now using the HTML file instead of generating it, I can use JavaScript to set my JWT token.
my token is not stored in JSON, so I did:
var key = localStorage.getItem("MyTokenName");
instead of
var key = JSON.parse(localStorage.getItem("MyTokenName"));