如何在Swagger编辑器中使用Cookies

时间:2016-04-28 19:55:51

标签: 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

1 个答案:

答案 0 :(得分:1)

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

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

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 Support Backlogthis issue了解更新。

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