Search code examples
cookiesswagger-editor

How to use Cookies in Swagger editor


I would like to document and test an API, which uses Cookie-based authetication in http://editor.swagger.io/. To give a simple example: How to write in the following YAML, that /login action creates a Cookie and the Cookie has to be passed to /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

Solution

  • Cookie authentication is supported in OpenAPI 3.0 but not in OpenAPI/Swagger 2.0.

    In OpenAPI 3.0, cookie authentication is defined as an API key that is sent 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
    

    The login operation is not linked to securitySchemes in any way, but you may want to define the response header Set-Cookie for documentation purposes:

    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
    

    That said, Swagger Editor and Swagger UI currently don't support cookie authentication. Check out the OAS 3.0 Support Backlog and this issue for updates.

    Cookie auth is supported in SwaggerHub though. (Disclosure: SwaggerHub is a product of the company I work for.)