Java swagger注解进行授权

20 *_*fps 1 java authorization swagger

我正在为我的其余 api 使用以下 swagger 依赖项:

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-rs-service-description-swagger</artifactId>
    <version>3.2.6</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>swagger-ui</artifactId>
    <version>3.17.6</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

现在我正在为我的项目添加安全性。如何实现使用 swagger 的 api 的可能性?

我可以为每种方法设置@HeaderParam(HttpHeaders.AUTHORIZATION)- 但我想有更好的方法吗?

20 *_*fps 5

现在我想与您分享我使用的工作解决方案:

@SwaggerDefinition(securityDefinition = @SecurityDefinition(
    apiKeyAuthDefinitions = {
            @ApiKeyAuthDefinition(
                    key = HttpHeaders.AUTHORIZATION,
                    name = HttpHeaders.AUTHORIZATION,
                    in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER
            )
    }
))
Run Code Online (Sandbox Code Playgroud)

它将为您的 Swagger UI 创建安全按钮来设置身份验证标头。现在您只需注释您想要保护的 api,如下所示:

@Api(value = "Your value", description = "Your description", authorizations = {
    @Authorization(HttpHeaders.AUTHORIZATION)
})
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用自定义标头,但对于我的解决方案,我使用了HttpHeaders.AUTHORIZATION.

所以我希望它会对某人有所帮助。