Swagger security schemes are how you tell the world (or at least, your API consumers) how to authenticate and authorize access to your endpoints.

Let’s see them in action. Imagine you have a simple API that serves user data. Here’s how you’d document its security requirements using Swagger/OpenAPI.

openapi: 3.0.0
info:
  title: User Data API
  version: 1.0.0
paths:
  /users/{userId}:
    get:
      summary: Get user by ID
      parameters:
        - in: path
          name: userId
          schema:
            type: integer
          required: true
          description: The ID of the user to retrieve
      security:
        - apiKeyAuth: [] # This endpoint requires an API Key
      responses:
        '200':
          description: User data retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '401':
          description: Unauthorized - Invalid API Key
  /oauth/token:
    post:
      summary: Obtain an OAuth2 access token
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              properties:
                grant_type:
                  type: string
                  enum: [client_credentials, password]
                client_id:
                  type: string
                client_secret:
                  type: string
                username: # Only for password grant
                  type: string
                password: # Only for password grant
                  type: string
      responses:
        '200':
          description: Access token granted
          content:
            application/json:
              schema:
                type: object
                properties:
                  access_token:
                    type: string
                  token_type:
                    type: string
                  expires_in:
                    type: integer
        '400':
          description: Invalid grant type or credentials

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header # API key is sent in the header
      name: X-API-Key # The name of the header field
    openIdConnectAuth:
      type: openIdConnect
      openIdConnectUrl: https://your-oidc-provider.com/.well-known/openid-configuration
    oauth2Auth:
      type: oauth2
      flows:
        clientCredentials: # Example for client_credentials flow
          tokenUrl: /oauth/token
          scopes:
            read:Users: Allows reading user data
        password: # Example for password grant type
          tokenUrl: /oauth/token
          scopes:
            read:Users: Allows reading user data
            write:Users: Allows writing user data

This components.securitySchemes section defines how to authenticate, and the security section under each path operation specifies which schemes are required for that operation.

The most surprising true thing about Swagger security schemes is that they don’t enforce security; they describe it. The actual authentication and authorization logic lives entirely within your API’s backend. Swagger just provides a standardized way to communicate those requirements to clients and developers.

Let’s break down the common types:

API Key

This is the simplest. A client sends a unique key (usually in a header or query parameter) that your API checks against a known list.

  • Problem Solved: Basic, static authentication. Good for internal services or when you need to identify specific clients without complex user management.
  • How it Works:
    1. Client obtains an API key from the service provider.
    2. Client includes the key in requests, typically X-API-Key: YOUR_SECRET_KEY in the header.
    3. API server receives the request, extracts the key from the header.
    4. API server looks up the key in its database/configuration.
    5. If the key is valid and authorized for the requested resource, the request proceeds. Otherwise, a 401 Unauthorized response is returned.
  • Levers:
    • type: Must be apiKey.
    • in: Where the key is located (query or header).
    • name: The name of the query parameter or header field (e.g., api_key, X-API-Key).
  • Example Usage:
    security:
      - apiKeyAuth: [] # Refers to the 'apiKeyAuth' scheme defined in components
    

OAuth2

OAuth2 is an authorization framework, not strictly an authentication protocol. It allows users to grant third-party applications limited access to their resources on another service, without giving them their credentials.

  • Problem Solved: Delegated authorization. Allows users to log in with one service (e.g., Google) and grant an app access to their data on another service (e.g., your API) without sharing their Google password.
  • How it Works:
    1. Authorization Request: The client application redirects the user to the authorization server (e.g., your /oauth/authorize endpoint).
    2. User Consent: The user logs into the authorization server and approves the client application’s request for specific scopes (permissions).
    3. Authorization Code: The authorization server redirects the user back to the client application with an authorization code.
    4. Token Request: The client application exchanges the authorization code (along with its client_id and client_secret) for an access token at the token endpoint (e.g., your /oauth/token).
    5. Resource Access: The client application uses the access token to make requests to your API’s protected resources. Your API validates the token with the authorization server or by checking its signature and expiry.
  • Levers:
    • type: Must be oauth2.
    • flows: Defines the supported OAuth2 grant types (e.g., authorizationCode, clientCredentials, password, implicit). Each flow has:
      • tokenUrl: The endpoint where the client exchanges codes/credentials for tokens.
      • authorizationUrl (for authorizationCode and implicit flows): The endpoint where users grant consent.
      • scopes: The available permissions the client can request.
  • Example Usage:
    security:
      - oauth2Auth: # Refers to the 'oauth2Auth' scheme
          - read:Users # Requesting the 'read:Users' scope
    
    Note that the oauth2Auth scheme itself might be configured with multiple flows (e.g., clientCredentials and password), and the security section specifies which scopes are needed for this specific operation.

OpenID Connect (OIDC)

OIDC is built on top of OAuth2. While OAuth2 is about authorization (what an application can do), OIDC is about authentication (verifying who the user is) and provides a standard way to get identity information.

  • Problem Solved: Standardized user authentication and identity information retrieval. Allows users to log in via a trusted Identity Provider (like Google, Auth0, or your own OIDC server) and provides the API with verified user identity claims.
  • How it Works:
    1. Discovery: The client uses the openIdConnectUrl to discover the OIDC provider’s endpoints (authorization, token, userinfo, JWKS).
    2. Authentication Request: The client redirects the user to the OIDC provider’s authorization endpoint, requesting an id_token and an access_token.
    3. User Authentication & Consent: The user logs into the OIDC provider.
    4. ID Token & Access Token: The OIDC provider returns an id_token (a JWT containing user identity claims like sub, name, email) and an access_token to the client.
    5. API Verification: The client sends the id_token or access_token to your API. Your API verifies the token’s signature against the OIDC provider’s public keys (obtained via the jwks_uri from the discovery document), checks its issuer and audience, and verifies its expiry. The id_token provides proof of authentication, and the access_token can be used for authorization.
  • Levers:
    • type: Must be openIdConnect.
    • openIdConnectUrl: The URL to the OIDC provider’s discovery document. This is crucial as it allows Swagger UI to dynamically fetch the necessary endpoints and keys.
  • Example Usage:
    security:
      - openIdConnectAuth: [] # Refers to the 'openIdConnectAuth' scheme
    
    When using OIDC, the security section usually just refers to the OIDC scheme. The id_token or access_token obtained from the OIDC provider is then typically passed in the Authorization: Bearer <token> header.

When you define these schemes in your OpenAPI document, tools like Swagger UI can automatically generate interactive forms for clients to input API keys, initiate OAuth2 flows, or provide bearer tokens, making your API much easier to consume and test.

Want structured learning?

Take the full Swagger course →