Cannot send Authorization Bearer Token using Springfox

后端 未结 7 858
无人及你
无人及你 2021-02-08 05:59

I\'m having trouble understanding why \"Authorization: Bearer __\" is not being sent in my api using Springfox 2.5.0. I have the following configuration:

private         


        
7条回答
  •  春和景丽
    2021-02-08 06:12

    A simple workaround is to type Bearer than paste the token after it. You will end up with a text box that contains:

    Bearer 
    

    I wish there was a more automated way. But for now, it appears as though what goes in the text box simple get's pasted into the value section of a given header entry. I suppose the reason the prefix Bearer does not get injected automatically is because then Swagger would be quite opinionated about which sort of authentication its users used!

    @Configuration
    @EnableSwagger2
    class SwaggerConfig {
    
        @Bean
        Docket api() {
    
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(Predicates.not(PathSelectors.regex("/error.*")))
                    .build()
                    .securitySchemes(securitySchemes())
        }
    
        private static ArrayList securitySchemes() {
    
            return [new ApiKey("Bearer", "Authorization", "header")]
        }
    }
    

    The REST endpoint method:

    @GetMapping("/count")
    @ApiOperation(value = "Count the number of entities associated with resource name. This operation does not requires any role." , authorizations = [@Authorization(value = "Bearer")])
    def count() {
    
        count(service)
    }
    

    The curl command before logging in:

    curl -X GET "http://localhost:8080/category/count" -H "accept: */*"
    

    Response:

    {
      "timestamp": "2018-10-29T15:13:02.388+0000",
      "status": 401,
      "error": "Unauthorized",
      "message": "Unauthorized",
      "path": "/category/count"
    }
    

    The curl command after logging in:

    curl -X GET "http://localhost:8080/category/count" -H "accept: */*" -H "Authorization: Bearer eyJhbGciOiJIUzUxMiJ9..."
    

    Response:

    {
      "message": "There are 0 entities",
      "count": 0
    }
    

    Note: My code is in Groovy, I am sure you can translate if you are using standard Java.

提交回复
热议问题