Swagger and JWT Token Authentication

前端 未结 2 1749
耶瑟儿~
耶瑟儿~ 2021-01-15 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 a

相关标签:
2条回答
  • 2021-01-16 00:06

    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.

    0 讨论(0)
  • 2021-01-16 00:16

    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.

    0 讨论(0)
提交回复
热议问题