【问题标题】:How to enable swagger to accept oauth2 tokens?如何让 swagger 接受 oauth2 令牌?
【发布时间】:2018-01-15 23:55:09
【问题描述】:

我正在使用jhipster 生成一个项目,现在我已经用

保护了一些端点
@PostMapping("/myEndpoint")
@PreAuthorize("#oauth2.hasScope('write')")

效果很好,但是我大摇大摆地看不到将令牌发送到哪里...

我之前使用过 swagger(没有配置它们),我知道这是可能的,但我不确定是 swagger 配置还是我的端点,知道吗?

【问题讨论】:

  • 你能分享一下你的招摇配置吗?

标签: spring swagger jhipster springfox


【解决方案1】:

你可以用类似的东西来注释你的方法

@ApiOperation(authorizations = {
    @Authorization(value = "my_oauth", scopes = {
        @AuthorizationScope(scope = "write")
    })
})

或者在带有 SecurityContext 的 springfox 案卷中使用正则表达式设置它(如果需要,调整正则表达式以覆盖多个端点)

private SecurityContext securityContext() {
    return SecurityContext.builder()
        .securityReferences(writeAuth())
        .forPaths(PathSelectors.regex("/myEndpoint"))
        .build();
}

List<SecurityReference> writeAuth() {
    AuthorizationScope authorizationScope
        = new AuthorizationScope("write", "");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return newArrayList(
        new SecurityReference("my_oauth", authorizationScopes));
}

您可能还想通过配置文档 SecuritySchemes 来定义 securityDefinitions

private OAuth oauth() {
    AuthorizationScope authorizationScope
        = new AuthorizationScope("write", "can write");
    return new OAuth("my_oauth", newArrayList(authorizationScope), newArrayList(new ResourceOwnerPasswordCredentialsGrant("/oauth/token")));
}

我认为现在在 jhipster 库中配置了默认的 docket,因此您将无法轻松自定义它,您可能必须创建一个新的 docket bean 来添加您的 SecuritySchemes 和 SecurityContext

@Bean
public Docket myApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .groupName("alt")
        .select()
        ...
        .securitySchemes(newArrayList(oauth()))
        .securityContexts(newArrayList(securityContext()))
        ;
}

您的新规范将在http://localhost:8080/v2/api-docs?group=alt 上提供

有关此的更多信息,请参阅 springfox 文档:http://springfox.github.io/springfox/docs/current/#getting-started-spring-boot

【讨论】:

    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2019-10-23
    相关资源
    最近更新 更多