如果需要身份验证,如何使用swagger测试Rest API调用

时间:2017-03-29 07:20:50

标签: spring swagger swagger-ui swagger-2.0 springfox

我在spring应用程序中有springfox-swagger2(版本2.6.1)和springfox-swagger-ui(版本2.6.1)。

如何为需要继续授权的呼叫配置授权令牌(如何为swagger设置X-AUTH-TOKEN)。

谢谢!

1 个答案:

答案 0 :(得分:1)

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

      现在要启用swagger UI,您需要提供以下bean配置

      new Docket(...)
          .securitySchemes(newArrayList(apiKey()))
          .securityContexts(newArrayList(securityContext()))
      

      这告诉swagger-ui您将在构建时使用api密钥并提供api身份验证令牌(可能使用加密配置属性。

      注意:swagger-ui的可配置性有限。它服务于80%的用例。额外的自定义可能意味着您无法使用捆绑的swagger-ui。