一个简单的解决方法是输入Bearer
而不是在其后粘贴令牌。您最终将得到一个文本框,其中包含:
Bearer <token>
我希望有一种更自动化的方式。但目前看来,文本框中的内容似乎已简单地粘贴到给定标头条目的值部分中。我想前缀的原因Bearer
不会自动注入是因为 Swagger 会对用户使用哪种身份验证非常有意见!
@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<? extends SecurityScheme> securitySchemes() {
return [new ApiKey("Bearer", "Authorization", "header")]
}
}
REST 端点方法:
@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
登录前命令:
curl -X GET "http://localhost:8080/category/count" -H "accept: */*"
回复:
{
"timestamp": "2018-10-29T15:13:02.388+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/category/count"
}
The curl
登录后命令:
curl -X GET "http://localhost:8080/category/count" -H "accept: */*" -H "Authorization: Bearer eyJhbGciOiJIUzUxMiJ9..."
回复:
{
"message": "There are 0 entities",
"count": 0
}
注意:我的代码是用 Groovy 编写的,如果您使用标准 Java,我相信您可以翻译。