jpganz18
jpganz18

Reputation: 5858

How to enable swagger to accept oauth2 tokens?

I am usinig jhipster to generate a project, now Ive secured some endpoints with

@PostMapping("/myEndpoint")
@PreAuthorize("#oauth2.hasScope('write')")

It works great but at swagger I cannot see where to send the token...

Ive worked with swagger before (didnt configure them) and I know is possible, but I am not sure if is a swagger config or is my endpoints, any idea?

Upvotes: 0

Views: 2302

Answers (1)

Christophe Bornet
Christophe Bornet

Reputation: 1127

You can annotate your method with something like

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

Or set it with regexp in a springfox docket with a SecurityContext (adapt the regexp to cover multiple endpoints if you want)

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));
}

You will also probably want to define the securityDefinitions by configuring the docket SecuritySchemes

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

I think that the default docket is now configured in the jhipster lib so you won't be able to customize it easily and you will probably have to create a new docket bean to add your SecuritySchemes and SecurityContext

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

Your new spec will be available at http://localhost:8080/v2/api-docs?group=alt

For more information about this, see the springfox doc : http://springfox.github.io/springfox/docs/current/#getting-started-spring-boot

Upvotes: 1

Related Questions