cookies - 如何在 Swagger 编辑器中使用 Cookie

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

最佳答案

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

在 OpenAPI 3.0 中,cookie 身份验证定义为发送的 API key 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 Support Backlogthis issue更新。

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

关于cookies - 如何在 Swagger 编辑器中使用 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36924317/

相关文章:

swagger - 如何从 swagger 定义中排除属性

Swagger: "equivalent path already exists"尽管参数不同

git - Swagger Editor 与 Git 或 GitHub 的集成

cookies - 尝试使用react和fetch获取然后发送cookie

javascript - JavaScript跨域PHP调用中的Cookie域是什么?

javascript - 无法在 Chrome 中设置/编辑 cookie

spring-boot - 当 API 中未发送必填字段值时,如何在 swagger 中自定义错误消息?

cookies - 如何在 apache camel 中设置 http 客户端 cookie 策略

java - 添加和读取cookie

swagger - 如何在 Swagger 2.0 中通过 body 发送默认值