如何在Swagger编辑器中使用Cookies

Jan*_*sen 6 cookies swagger-editor

我想记录和测试一个API,它在http://editor.swagger.io/中使用基于Cookie的认证.举一个简单的例子:如何在下面的YAML中编写,/ login操作创建一个Cookie并且Cookie必须传递给/ showMySecretStuff?

swagger: '2.0'
info:
  title: Test API
  version: '1'
host: my.test.com
schemes:
  - https
basePath: /
consumes:
  - multipart/form-data
produces:
  - application/json
paths:
  /login:
    post:
      parameters:
        - name: username
          in: formData
          required: true
          type: string
        - name: password
          in: formData
          required: true
          type: string
          default: secret
      responses:
        200:
          description: OK
  /showMySecretStuff:
    get:
      responses:
        200:
          description: OK
Run Code Online (Sandbox Code Playgroud)

Hel*_*len 2

OpenAPI 3.0 支持 Cookie 身份验证,但 OpenAPI/Swagger 2.0 不支持。

在 OpenAPI 3.0 中,cookie 身份验证定义为发送的 API 密钥in: cookie

openapi: 3.0.1
...

components:
  securitySchemes:
    cookieAuth:
      type: apiKey
      in: cookie
      name: COOKIE-NAME  # replace with your cookie name

paths:
  /showMySecretStuff:
    get:
      security:
        - cookieAuth: []
      responses:
        '200':
          description: OK
Run Code Online (Sandbox Code Playgroud)

登录操作不以securitySchemes任何方式链接,但您可能需要定义响应标头Set-Cookie以用于文档目的:

paths:
  /login:
    post:
      requestBody:
        ...
      responses:
        '200':
          description: OK
          headers:
            Set-Cookie:
              description: >
                Contains the session cookie named `COOKIE-NAME`.
                Pass this cookie back in subsequent requests.
              schema: 
                type: string
Run Code Online (Sandbox Code Playgroud)

也就是说,Swagger Editor 和 Swagger UI 目前不支持 cookie 身份验证。查看OAS 3.0 支持待办事项列表本期的更新。

不过SwaggerHub支持 Cookie 身份验证。(披露:SwaggerHub 是我工作的公司的产品。)