Security schemes

OpenAPI · Practical · 12 min

Docs consoles, SDKs and gateways all need to know how to authenticate.

Authentication is described in two steps: define schemes under components.securitySchemes, then require them with security.

Scheme types:

  • apiKey: a key in a header, query parameter or cookie (in: header, name: X-API-Key).
  • http: standard HTTP auth with scheme: bearer (optionally bearerFormat: JWT) or scheme: basic.
  • oauth2: one or more flows (authorizationCode, clientCredentials, deviceAuthorization in 3.2) with URLs and the available scopes.
  • openIdConnect: an openIdConnectUrl pointing at the provider's discovery document.
  • mutualTLS (3.1+).

A security requirement is a map of scheme names to required scopes: - oauth: [books.read]. Semantics to get right:

  • Entries in the security list are alternatives (OR).
  • Several schemes in one entry must all be satisfied (AND).
  • Top-level security applies to every operation; an operation-level security replaces it. security: [] marks an operation as public, and - {} inside the list makes authentication optional.

Security schemes only describe what the API expects; they do not enforce anything. Never put real credentials in the document or its examples.

Example

components:
  securitySchemes:
    apiKey: { type: apiKey, in: header, name: X-API-Key }
    oauth:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/authorize
          tokenUrl: https://auth.example.com/token
          scopes:
            books.read: Read the catalogue
            books.write: Change the catalogue
security:                      # default: OAuth OR API key
  - oauth: [books.read]
  - apiKey: []
paths:
  /health:
    get:
      security: []             # public endpoint
      responses: { '200': { description: OK } }
  /books:
    post:
      security:
        - oauth: [books.write] # overrides the default
      responses: { '201': { description: Created } }

Remember

  • Define schemes in components, require them with security
  • List entries are OR; schemes within one entry are AND
  • Operation security overrides the global one; [] = public
  • OAuth scopes are declared on the scheme and required per operation

Watch out for

  • Listing two schemes as separate entries when the API actually needs both (AND).

Check yourself

  1. `security: [{apiKey: []}, {oauth: [read]}]` means the client must provide...

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.openapis.org/specification/security.html