【问题标题】:How to test Rest API call with swagger if needs authentication如果需要身份验证,如何使用 swagger 测试 Rest API 调用
【发布时间】: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


    【解决方案1】:
    1. 将以下 API 密钥定义为安全方案。在您的原因中,有一个名为X-AUTH-TOKEN 的标题。我们使用密钥mykey 引用此方案。
    private ApiKey apiKey() {
      return new ApiKey("mykey", "X-AUTH-TOKEN", "header");
    }
    
    1. 设置安全上下文。这只是意味着您正在为 API 中的给定路径设置授权范围。例如对于/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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2017-12-14
      • 2017-07-28
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多