Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Security Schemes

OpenAPI OAuth 2.0 and OpenID Connect: Flows, Scopes and PKCE

Describe OAuth 2.0 and OpenID Connect in OpenAPI: authorizationCode, clientCredentials and other flows, scopes per operation, openIdConnectUrl, mutualTLS and a PKCE demo.

When an app acts on behalf of a user, or when you need fine-grained permissions, a key or a bare token is not enough. OAuth 2.0 is the industry standard for delegated access, and OpenID Connect (OIDC) adds identity on top of it. OpenAPI describes both so that documentation tools can run the login flow for you and generators can fetch tokens.

OpenAPI only describes the flows. It does not implement an authorization server. Describing a flow correctly means copying the real endpoint URLs and scopes of your identity provider (for example your own auth server, Keycloak, Auth0 or Entra ID) into the document.

The oauth2 scheme

YAML
components:
  securitySchemes:
    OAuth2:
      type: oauth2
      description: Sign in with the company account.
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/authorize
          tokenUrl: https://auth.example.com/token
          refreshUrl: https://auth.example.com/token
          scopes:
            pets:read: Read pets
            pets:write: Create and change pets
        clientCredentials:
          tokenUrl: https://auth.example.com/token
          scopes:
            pets:read: Read pets

flows can contain one or several flow objects. Each flow type has its own required URLs:

Flow Needs Typical use
authorizationCode authorizationUrl, tokenUrl, scopes Web, mobile and single-page apps acting for a user (use with PKCE)
clientCredentials tokenUrl, scopes Server-to-server, no user
implicit authorizationUrl, scopes Legacy; avoid in new APIs
password tokenUrl, scopes Legacy; avoid in new APIs

(OpenAPI 3.2 adds a device authorization flow for TVs and consoles; check that your tools support it before using it.) scopes is a map of scope name to a short human description and is required even if it is empty ({}).

sequenceDiagram
  participant U as User
  participant A as Client app
  participant S as Authorization server
  participant R as Your API
  A->>S: redirect to authorizationUrl (+ code_challenge)
  S->>U: login and consent
  U->>S: approve scopes
  S->>A: redirect back with code
  A->>S: tokenUrl: code + code_verifier
  S->>A: access token (and refresh token)
  A->>R: Authorization: Bearer access token

The authorization code flow with PKCE: the sequence the "Authorize" button in documentation tools can run for you.

Scopes in security requirements

Scopes are listed in the security requirement, per operation:

YAML
paths:
  /pets:
    get:
      security:
        - OAuth2: [pets:read]
    post:
      security:
        - OAuth2: [pets:write]
  /pets/{petId}:
    delete:
      security:
        - OAuth2: [pets:write, pets:admin]   # needs BOTH scopes

All scopes listed in one requirement must be granted. Scopes used in a requirement should be declared in the scheme's flows.

OpenID Connect

If your provider publishes an OIDC discovery document, point to it and let tools find the endpoints themselves:

YAML
components:
  securitySchemes:
    OIDC:
      type: openIdConnect
      openIdConnectUrl: https://auth.example.com/.well-known/openid-configuration

Requirements use scope names from that provider (openid, profile, email, plus yours):

YAML
security:
  - OIDC: [openid, profile]

Mutual TLS

OpenAPI 3.1 can state that clients authenticate with a TLS certificate:

YAML
components:
  securitySchemes:
    ClientCert:
      type: mutualTLS
      description: Present a certificate issued by the Example CA.

PKCE: the part that protects the code

Public clients (mobile apps, single-page apps) cannot keep a secret, so the authorization code flow uses PKCE (Proof Key for Code Exchange). The client creates a random code_verifier, sends its SHA-256 hash as code_challenge when it starts the flow, and later proves it owns the code by sending the original verifier to the token URL. Even if someone steals the code from the redirect, they cannot use it without the verifier.

This stand-in computes a challenge exactly the way the standard defines it (method S256) and shows the verification the authorization server performs.

Python Stand-in: compute and verify a PKCE challenge

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.

Practical advice

  • Prefer authorizationCode with PKCE for anything that involves a user, and clientCredentials for back-end jobs.
  • Do not describe implicit or password flows for new APIs: current security guidance (OAuth 2.0 Security Best Current Practice and OAuth 2.1) removes them.
  • Keep scopes small and meaningful (pets:read, pets:write), named in a consistent resource:action style.
  • Use openIdConnect when your provider has a discovery URL; it avoids copying endpoint URLs that can change.
  • In Swagger UI, the Authorize button for an OAuth scheme starts the flow in a pop-up; set the client id in the dialog (never in the document). Some tools let you pre-fill a public client id, never a client secret.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which flow is meant for server-to-server calls with no user involved?

    clientCredentials exchanges the app's own credentials for a token.
  2. 2. Where do you name the scopes an operation needs?

    Scopes go in the list after the scheme name, e.g. OAuth2: [pets:write].
  3. 3. What does openIdConnectUrl point to?

    Tools read the discovery document to find endpoints.
  4. 4. What problem does PKCE solve?

    The client proves it started the flow by presenting the verifier that hashes to the challenge.
  5. 5. Which flows should you avoid describing for new APIs?

    Both are legacy and removed from OAuth 2.1.

Summary

  • type: oauth2 describes flows (authorizationCode, clientCredentials, legacy implicit/password) with their URLs and a scopes map.
  • Operations request scopes through security entries such as OAuth2: [pets:write].
  • openIdConnect points at a discovery URL; mutualTLS describes client certificates.
  • Authorization code with PKCE is the standard for apps acting for users.
  • OpenAPI describes, your authorization server and API enforce.

Next: back to the OpenAPI and Swagger track overview