【问题标题】:Add authorization header to Springfox将授权标头添加到 Springfox
【发布时间】:2017-05-24 05:42:57
【问题描述】:

我正在使用带有 Angular 2 前端的 spring boot,我想为我的 swagger 配置添加授权。

我当前的 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 添加它?

【问题讨论】:

  • 为什么你没有那个选项,因为你使用的是 springfox?
  • 它正在生成 HTML 文件

标签: angular spring-boot jwt swagger-ui springfox


【解决方案1】:

我有两个依赖项,springfox-swagger2 和 springfox-swagger-ui。我最终删除了 springfox-swagger-ui 依赖项。

Jhipster 使用了一个示例,他们从 springfox-swagger2 对打包的 swagger 文件进行 Get 调用。我可以通过一些小的改动来使用这个例子。

我将 swagger-ui 配置添加到我的公用文件夹中。由于我现在使用的是 HTML 文件而不是生成它,因此我可以使用 JavaScript 来设置我的 JWT 令牌。

我的令牌没有存储在 JSON 中,所以我这样做了:

var key = localStorage.getItem("MyTokenName");

而不是

var key = JSON.parse(localStorage.getItem("MyTokenName"));

【讨论】:

    【解决方案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 */);
    }
    

    您可以找到更多信息here

    【讨论】:

    • 查看文档的 2.1.3 Springfox-swagger2 with Spring MVC and Spring Boot 章节,也许它会有所帮助。这个 SecurityConfiguration bean 声明在我的 spring mvc + spring security + swagger + jwt 实现中工作。
    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2023-03-23
    • 1970-01-01
    • 2018-12-25
    • 2021-07-22
    相关资源
    最近更新 更多