6

我想记录和测试一个 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
4

1 回答 1

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

登录操作未以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

也就是说,Swagger Editor 和 Swagger UI 目前不支持 cookie 身份验证。查看OAS 3.0 支持积压此问题以获取更新。

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

于 2017-09-27T16:59:38.080 回答