java - 无法使用 Springfox 发送授权承载 token

标签 java spring swagger swagger-ui springfox

我无法理解为什么使用 Springfox 2.5.0 没有在我的 api 中发送“Authorization: Bearer __”。我有以下配置:

private ApiKey apiKey() {
        return new ApiKey(
                "Authorization", // name: My key - Authorization
                "api_key", // keyname: api_key
                "header");
    }

@Bean
    SecurityConfiguration security() {
        return new SecurityConfiguration(
                null, null, null,
                "Docserver2_fwk", // app name
                "BEARER", // api key value
                ApiKeyVehicle.HEADER, "Authorization", ",");
    }

enter image description here 发送的 curl 是:

enter image description here

似乎我无法在 springfox (2.5.0) 中发送“Authorization: Bearer Token”,这可能吗?这是一个已知问题吗?

类似问题:https://github.com/springfox/springfox/issues/1812

PS:OpenAPI 3.0 允许“bearer”格式,例如:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#jwt-bearer-sample

谢谢。

最佳答案

一个简单的解决方法是键入 Bearer 而不是在其后粘贴 token 。您最终会得到一个包含以下内容的文本框:

Bearer <token>

enter image description here

我希望有一种更自动化的方式。但就目前而言,似乎文本框中的内容被简单地粘贴到给定标题条目的值部分。我想前缀 Bearer 没有被自动注入(inject)的原因是因为 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)
}

登录前的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"
}

登录后的curl命令:

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

响应:

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

注意:我的代码是用 Groovy 编写的,如果您使用的是标准 Java,我相信您可以翻译。

关于java - 无法使用 Springfox 发送授权承载 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48442416/

相关文章:

java - Spring CGLib代理-类变量变为null

java - Java 中的圆形 Pane

java - 如何在 Hibernate - Criteria Queries 中获得大于记录?

java - Spring 重试使用 XML 配置的 DAO 调用

google-cloud-platform - GCP API网关JWT始终返回403

java - 使用循环创建多个对象

java - 为什么 JPA API Path.get(MapAttribute) 和 Path.get(PluralAttribute) 参数中没有 "? super X"?

java - Tomcat 7 - 无法找到 mysql 驱动程序

ruby-on-rails - 如何从 swagger 发送 header 参数

node.js - 更改 swagger 2.0 文档路径 url