Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Security Schemes

OpenAPI Security Schemes: Defining and Applying Authentication

Describe API authentication in OpenAPI: securitySchemes in components, the security requirement object, global versus per-operation security, AND/OR logic and public endpoints.

An API description that ignores authentication is only half a description. Clients need to know how to prove who they are, and which operations need that proof. OpenAPI separates this into two steps: define a scheme under components.securitySchemes, then apply it with a security requirement.

Step 1: define the schemes

YAML
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/authorize
          tokenUrl: https://auth.example.com/token
          scopes:
            pets:read: Read pets
            pets:write: Modify pets

Each scheme has a name you choose (ApiKeyAuth) and a type:

type Used for
apiKey A key in a header, query string or cookie
http HTTP authentication: basic, bearer, digest...
oauth2 OAuth 2.0 flows with scopes
openIdConnect OAuth 2.0 discovered from an OpenID Connect URL
mutualTLS Client certificates (3.1)

Defining a scheme does not protect anything. It is only a named definition. The next lessons cover each type in detail: API key, basic and bearer and OAuth 2.0 and OpenID Connect.

Step 2: apply the schemes with security

A security requirement is a list of objects; each object maps a scheme name to a list of scopes (empty for non-OAuth schemes).

YAML
# Global: applies to every operation unless overridden
security:
  - BearerAuth: []

paths:
  /pets:
    get:
      # inherits the global requirement
      responses: { "200": { description: OK } }
    post:
      # overrides it: needs OAuth2 with a scope
      security:
        - OAuth2: [pets:write]
      responses: { "201": { description: Created } }
  /health:
    get:
      # public endpoint: an empty list removes security
      security: []
      responses: { "200": { description: OK } }

AND and OR

The structure has two levels, and the logic is easy to misread:

YAML
security:
  - ApiKeyAuth: []          # option 1 ...
  - BearerAuth: []          # ... OR option 2

security:
  - ApiKeyAuth: []          # one option that needs BOTH ...
    BasicAuth: []           # ... ApiKeyAuth AND BasicAuth together
  • List items are alternatives (OR): the caller satisfies any one item.
  • Keys inside one item must all be satisfied (AND).

You can also mark authentication optional by adding an empty object {} as an alternative:

YAML
security:
  - {}                      # anonymous callers allowed
  - BearerAuth: []          # or authenticated callers

Evaluate requirements with a stand-in

This stand-in decides whether a request (described by the credentials it carries) satisfies an operation's security requirement, including AND/OR logic and OAuth scopes.

Python Stand-in: does this request satisfy the security requirement?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What OpenAPI does and does not do

  • It describes authentication so that documentation tools can show an Authorize button, generators can add credentials to requests, and gateways and scanners can check your policy.
  • It does not enforce anything. The server must still verify tokens and scopes.
  • Credentials themselves never belong in the document. Do not put real keys or tokens into example values or default.

Where Swagger UI shows security

Tools that read the document display a padlock icon on protected operations and an Authorize dialog that stores the key or token and attaches it to Try it out calls. If the padlock is missing, check that the operation (or the root) really has a security entry.

Document the failures too

Add the responses a client needs when authentication fails:

YAML
responses:
  "401":
    description: Missing or invalid credentials
    headers:
      WWW-Authenticate:
        schema: { type: string }
  "403":
    description: Authenticated but not allowed (missing scope)

Put the common scheme in the root security and mark the few public endpoints with security: []. It is far safer than the opposite, because a forgotten operation is then protected by default.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where are security schemes defined?

    Schemes are defined under components.securitySchemes and applied with security.
  2. 2. What does security: [] on an operation mean?

    An empty list overrides the global requirement.
  3. 3. In security: [ {A: []}, {B: []} ], the caller must...

    Separate list items are alternatives (OR).
  4. 4. In security: [ {A: [], B: []} ], the caller must...

    Keys inside one object are combined with AND.
  5. 5. Does defining a securityScheme protect an endpoint on its own?

    Schemes describe; requirements apply; servers enforce.

Summary

  • Define schemes in components.securitySchemes (types: apiKey, http, oauth2, openIdConnect, mutualTLS).
  • Apply them with security globally or per operation; security: [] makes an operation public.
  • List items are OR; keys inside one item are AND; {} allows anonymous access.
  • OpenAPI only describes security; the server must enforce it.

Next: API key, basic and bearer authentication