SkillByAIOpen interactive version →

Lesson 11 / 25

OAuth 2.0 and OpenID Connect in OpenAPI

Describe OAuth flows and scopes and require scopes per operation.

Delegated authorisation with scopes

For OAuth 2.0, an oauth2 security scheme lists flows with their URLs and available scopes. The authorization code flow (used with PKCE by browser and mobile apps) has an authorizationUrl and a tokenUrl; the client credentials flow, for service-to-service calls, has a tokenUrl. The older implicit and password flows are discouraged by current OAuth security guidance and are omitted from OAuth 2.1, so avoid documenting new APIs with them. Scopes are named permissions such as orders:read and orders:write, each with a description. Operations list the scopes they require: security: [ { oauth: [orders:write] } ]. An openIdConnect scheme instead points to the provider's discovery document (/.well-known/openid-configuration), from which tools learn the endpoints. Interactive documentation such as Swagger UI can then run the OAuth flow and obtain a token for "try it out" requests, which is very helpful for integrators; configure a dedicated documentation client in your identity provider with appropriate redirect URIs.

OAuth 2.0 flows with scopes

Authorization code for users, client credentials for services; scopes required per operation.

components:
  securitySchemes:
    oauth:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/oauth2/authorize
          tokenUrl: https://auth.example.com/oauth2/token
          scopes:
            orders:read: Read your orders
            orders:write: Create and cancel your orders
        clientCredentials:
          tokenUrl: https://auth.example.com/oauth2/token
          scopes:
            orders:read: Read orders for fulfilment
    oidc:
      type: openIdConnect
      openIdConnectUrl: https://auth.example.com/.well-known/openid-configuration

paths:
  /orders:
    get:
      operationId: listOrders
      security:
        - oauth: [orders:read]
      responses: { '200': { description: Orders } }
    post:
      operationId: createOrder
      security:
        - oauth: [orders:write]
      responses: { '201': { description: Created } }

A hotel key card with floor access

The OAuth token is a key card; scopes are the floors it opens. The OpenAPI document is the hotel guide stating which floors each room needs, so guests know which card to request.

Quick check: Which OAuth flow suits a backend service calling another service with no user involved?

  • Implicit
  • Client credentials
  • Authorization code with PKCE
  • Password
Answer

Client credentials — Client credentials is the machine-to-machine flow.