Search code examples
openapiswagger-ui

How to correctly declare a route with facultative authentication in OpenAPI 3.0 specification?


I have a route that returns the content of a public article. If the user is logged, the route returns a different content (a content with additionnal details). I don't know how to declare this in my OpenAPI description. I couldn't find anything about this in the official doc.

My securitySchemes definition :

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

My route declaration :

 /article/{slug}:
    get:
      tags:
        - articles
      summary: Return an article with more detail for authenticated users
      operationId: get_detail_article
      parameters:
        - name: slug
          in: path
          required: true
          schema:
            type: string
      security: 
        - {}
        - bearerAuth: []
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Article"

Is the authentification part is correct ?

the result in swagger editor :

enter image description here

As you can see, the lock at right is black and closed, meaning that authentification is necessary.


Solution

  • Not sure which Swagger Editor version you are using but the security object is defined correctly for an OR condition, as in.. must use bearerAuth OR none

    openapi: 3.0.3
    info:
      title: test
      version: 1.0.0
    servers:
      - url: https://www.example.com
    paths:
      "/article/{slug}":
        get:
          tags:
            - articles
          summary: Return an article with more detail for authenticated users
          operationId: get_detail_article
          parameters:
            - name: slug
              in: path
              required: true
              schema:
                type: string
          security:
            - {}
            - bearerAuth: []
          responses:
            "200":
              description: OK
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/Article"
    components:
      securitySchemes:
        bearerAuth:
          type: http
          scheme: bearer
          bearerFormat: JWT
      schemas:
        Article:
          description: An Article
          type: string
    

    I get a transparent lock on Swagger UI free account unlocked

    If I comment out the empty security, the lock changes to require only bearerAuth locked