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 withscheme: bearer(optionallybearerFormat: JWT) orscheme: basic.oauth2: one or moreflows(authorizationCode,clientCredentials,deviceAuthorizationin 3.2) with URLs and the available scopes.openIdConnect: anopenIdConnectUrlpointing 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
securitylist are alternatives (OR). - Several schemes in one entry must all be satisfied (AND).
- Top-level
securityapplies to every operation; an operation-levelsecurityreplaces 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
securityoverrides 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).