Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 275
Jansen Avatar asked Apr 28 '16 19:04

Jansen


People also ask

How do I pass cookies in HTTP request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

What are restful API cookies?

A cookie is a piece of data that a server sends in the HTTP response. The client (optionally) stores the cookie and returns it on subsequent requests. This allows the client and server to share state. To set a cookie, the server includes a Set-Cookie header in the response.


1 Answers

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.)

like image 98
Helen Avatar answered Oct 08 '22 20:10

Helen