简体   繁体   中英

Add a swagger annotation for bearer auth

I am working on a dropwizard REST service. I have added authentication with a jwt using https://bitbucket.org/b_c/jose4j/wiki/Home

The token has to be into the Authorization header

Authorization: Bearer [TOKEN]

I would like to find the good way to add some swagger annotations to have the authorization header on the swagger-ui.

I have found a work around, hiding the authentication param and adding a dummy param with @HeaderParam

@POST
@Path("/test/")
public Foo postBar(
        @Auth @ApiParam(hidden = true) Principal user,
        @ApiParam("data") Foo bar,
        @HeaderParam(value="Authorization")String dummy)

This will add into the parameters:

{
  "name" : "Authorization",
  "in" : "header",
  "required" : false,
  "type" : "string"
} 

If I put the @HeadParam for Principal user I get on run time:

Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.

[[FATAL] No injection source found for a parameter of type public java.util.Map com.foo.bar.AppResource.get(java.security.Principal) at index 0.; source='ResourceMethod{httpMethod=GET, consumedTypes=[], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.mykronoz.data.tracking.resources.AppResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@6374d682]}, definitionMethod=public java.util.Map com.foo.bar.AppResource.get(java.security.Principal), parameters=[Parameter [type=interface java.security.Principal, source=Authorization, defaultValue=null]], responseType=java.util.Map<java.lang.String, java.lang.Object>}, nameBindings=[]}']

Is there a better way to do that ?

If you add a swaggerdefinition

@SwaggerDefinition(
  securityDefinition = @SecurityDefinition(
    apiKeyAuthDefinitions = {
      @ApiKeyAuthDefinition(key = "user", name = "Authorization", in = ApiKeyLocation.HEADER)
    }
  )
)

you will then get access to the 'Authorize' feature of the swagger ui. Adding your "Bearer XXX...." string as an API key should then cause the endpoint to be called with the Authorize header set the way you want and the user field set to its value.

Warning: I haven't seen this working end-to-end yet because I am having issues with the token itself, but it appears that I am getting the correct things passed through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM