21

如何使用 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);
    }
}
4

3 回答 3

21

使用 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 注释来为您需要身份验证的操作设置基本身份验证:

@ApiOperation(value = "Return list of categories", response=Category.class, responseContainer="List", httpMethod="GET", authorizations = {@Authorization(value="basicAuth")})
public Response getCategories();
于 2017-05-28T13:35:11.153 回答
5

我也为此苦苦挣扎。就我而言,我使用了 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"
    }
  }

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

于 2016-10-26T15:36:05.660 回答
0

您可以使用@SwaggerDefinition http://swagger.io/customizing-your-auto-generated-swagger-definitions-in-1-5-x/

或者您可以直接配置 swagger 对象,这是一个示例 http://www.programcreek.com/java-api-examples/index.php?source_dir=rakam-master/rakam/src/main/java/org/rakam/ WebServiceRecipe.java

于 2017-04-26T04:53:41.990 回答