我如何在 Swagger 规范 (swagger.json) 中表示 'Authorization: Bearer <token>'

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

我想表达的是 authentication/security 方案需要设置 header 如下:

Authorization: Bearer <token>

这是我根据 swagger documentation:

securityDefinitions:
  APIKey:
    type: apiKey
    name: Authorization
    in: header
security:
  - APIKey: []

也许这可以帮助:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

您可以将其复制并粘贴到此处:http://editor.swagger.io/#/ 以查看结果。

swagger editor web 中还有几个示例,其中包含更复杂的安全配置,可以帮助您。

为什么 "Accepted Answer" 有效...但对我来说还不够

这在规范中有效。至少 swagger-tools(版本 0.10.1)将其验证为有效。

但如果您使用其他工具,如 swagger-codegen(版本 2.1.6),您会发现一些困难,即使生成的客户端包含身份验证定义,如下所示:

this.authentications = {
  'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};

在调用方法(端点)之前无法将令牌传递到 header。查看此函数签名:

this.rootGet = function(callback) { ... }

这意味着,我只在没有令牌的情况下传递回调(在其他情况下是查询参数等),这会导致对服务器的请求构建不正确。

我的选择

不幸的是,它不是 "pretty",但它一直有效,直到我在 Swagger 上获得 JWT 令牌支持。

注:

中正在讨论

因此,它像标准 header 一样处理身份验证。在 path object 上附加一个 header 参数:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: localhost
schemes:
  - http
  - https
paths:
  /:
    get:
      parameters:
        - 
          name: authorization
          in: header
          type: string
          required: true
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

这将在方法签名上生成一个带有新参数的客户端:

this.rootGet = function(authorization, callback) {
  // ...
  var headerParams = {
    'authorization': authorization
  };
  // ...
}

要正确使用此方法,只需将 "full string"

// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);

并且有效。

Bearer authentication in OpenAPI 3.0.0

OpenAPI 3.0 now supports Bearer/JWT authentication natively. It's defined like this:

openapi: 3.0.0
...

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT  # optional, for documentation purposes only

security:
  - bearerAuth: []

This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.0 specs only!).

UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx header.

Adding Authorization header programmatically (Swagger UI 3.x)

If you use Swagger UI and, for some reason, need to add the Authorization header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor. This solution is for Swagger UI 3.x; UI 2.x used a different technique.

// index.html

const ui = SwaggerUIBundle({
  url: "http://your.server.com/swagger.json",
  ...

  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer xxxxxxx"
    return req
  }
})

使用 openapi 3.0.0 在 JSON 中发布 2022 年答案:

{
  "openapi": "3.0.0",
  ...
  "servers": [
    {
      "url": "/"
    }
  ],
  ...
  "paths": {
    "/skills": {
      "put": {
        "security": [
           {
              "bearerAuth": []
           }
        ],
       ...
  },


  "components": {        
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  }
}

我的 Hackie 解决这个问题的方法是在我的例子中修改 echo-swagger 包中的 swagger.go 文件:

在文件底部更新 window.onload 函数以包含正确格式化令牌的 requestInterceptor。

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
  url: "{{.URL}}",
  dom_id: '#swagger-ui',
  validatorUrl: null,
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ,
  layout: "StandaloneLayout",
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization
  return req
  }
})

window.ui = ui

}

通过使用 requestInterceptor,它对我有用:

const ui = SwaggerUIBundle({
  ...
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization;
    return req;
  },
  ...
});

从 laravel 7x ("openapi": "3.0.0") 解决这个问题,使用以下代码编辑您的 config\l5-swagger.php

'securityDefinitions' => [
                'securitySchemes' => [
                    'bearerAuth' => [ 
                        'type' => 'http',
                        'scheme' => 'bearer',
                        'bearerFormat' => 'JWT', 
                    ], 
                ],

然后您可以将其添加为端点的安全注释:

*security={
     *{
     *"bearerAuth": {}},
     *},