【问题标题】:Swagger 2.0 where to declare Basic Auth SchemaSwagger 2.0 在哪里声明 Basic Auth Schema
【发布时间】:2015-11-29 19:28:42
【问题描述】:

如何使用 Swagger 2.0 注释定义基本身份验证并将其显示在 Swagger UI 中。

在我拥有的资源中:

@ApiOperation(value = "Return list of categories", response=Category.class, responseContainer="List", httpMethod="GET", authorizations = {@Authorization(value="basicAuth")})
public Response getCategories();

我看过这里:

https://github.com/swagger-api/swagger-core/wiki/Annotations#authorization-authorizationscope

它说“一旦您声明并配置了您在 API 中支持的授权方案,您就可以使用这些注释来记录资源或特定操作需要哪种授权方案”但我找不到任何东西讨论在哪里声明和配置授权方案。

更新:

我找到了有关如何声明架构的代码,但我仍然没有在 UI 中看到任何有关身份验证架构的信息。我不确定我错过了什么

@SwaggerDefinition
public class MyApiDefinition implements ReaderListener {
    public static final String BASIC_AUTH_SCHEME = "basicAuth";

    @Override
    public void beforeScan(Reader reader, Swagger swagger) {
    }

    @Override
    public void afterScan(Reader reader, Swagger swagger) {
        BasicAuthDefinition basicAuthDefinition = new BasicAuthDefinition();
        swagger.addSecurityDefinition(BASIC_AUTH_SCHEME, basicAuthDefinition);
    }
}

【问题讨论】:

    标签: swagger swagger-ui swagger-2.0


    【解决方案1】:

    使用 Springfox 2.6 注解,在配置中设置 Docket 时,必须首先将基本身份验证定义为安全方案之一,如下所示:

    List<SecurityScheme> schemeList = new ArrayList<>();
    schemeList.add(new BasicAuth("basicAuth"));
    
    return new 
      Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo)
                                         .securitySchemes(schemeList)
                                         ...
    

    然后你可以在你的服务中使用 Springfox 注解来为你想要认证的操作设置 Basic Auth:

    @ApiOperation(value = "Return list of categories", response=Category.class, responseContainer="List", httpMethod="GET", authorizations = {@Authorization(value="basicAuth")})
    public Response getCategories();
    

    【讨论】:

      【解决方案2】:

      我也为此苦苦挣扎。就我而言,我使用了 swagger-maven-plugin。为了解决这个问题,我在 maven 插件中添加了这个:

      <securityDefinitions>
        <securityDefinition>
          <name>basicAuth</name>
          <type>basic</type>
        </securityDefinition>
      </securityDefinitions>
      

      之后我可以像这样将它添加到我的资源中:

      @Api(value = "My REST Interface", authorizations = {@Authorization(value="basicAuth")})
      

      生成的 json 包含每个端点的安全元素:

      "security":[{
        "basicAuth" : []
       }]
      

      以及安全定义:

        "securityDefinitions" : {
          "basicAuth" : {
            "type" : "basic"
          }
        }
      

      我希望这对其他人也有帮助。

      【讨论】:

        【解决方案3】:
        猜你喜欢
        • 2021-03-08
        • 2014-02-25
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-29
        • 2015-08-30
        • 1970-01-01
        相关资源
        最近更新 更多