Swagger and JWT Token Authentication

2019-02-20 23:52发布

问题:

I am building some Swagger documentation, all well and good, except that I am wanting to have the page work interactively, so when selecting the editor or UI, if I hit the authorize button, I would call my Authentication URL that builds the JWT token that is then used in subsequent requests.

I am planning to issue the API client an Api Access Key and a Secret Access Key, and want to hit an authentication page that will process these and build the JWT token.

It strikes me that if I can get the correct definition of how to achieve this in Swagger, that I will have a ready-built test client to then use against my fresh new code.

Yes, it's my first time with JWT and I have not yet built the code. Can you say "API-First"?

回答1:

This is how I used Swagger with JWT Authentication:

  • Write a Express.js API end point to generate a JWT.
  • Create a Swagger Path to retrieve the JWT using above end point
  • In swagger.yaml root level:

    securityDefinitions:  
      JWT:  
        type: apiKey  
        in: header  
        name: access_token  
    
  • In swagger.yaml paths:

    security  
     -JWT: []
    

This will display an Authorize button in Swagger UI on browser.

  • Enter JWT generated above in the Authentication Window that pops-up when above Authorize button is clicked
  • Now JWT will be passed with the request headers

Hope this may help others.



回答2:

It is possible with Swagger to save your token and automatically apply the token to all your request.

Here is what you need to add to your Swagger Docket Configuration:

@Bean
public Docket newsApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Lists.newArrayList(apiKey()))
            .securityContexts(Lists.newArrayList(securityContext()))
            .apiInfo(generateApiInfo());
}

@Bean
SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("JWT", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("JWT", "Authorization", "header");
}

You will then be able to see the Authorize button when your Swagger UI is loaded.

You can save your token, make sure you add the 'Bearer ' in front of your token.