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:
- Client obtains an API key from the service provider.
- Client includes the key in requests, typically
X-API-Key: YOUR_SECRET_KEYin the header. - API server receives the request, extracts the key from the header.
- API server looks up the key in its database/configuration.
- If the key is valid and authorized for the requested resource, the request proceeds. Otherwise, a
401 Unauthorizedresponse is returned.
- Levers:
type: Must beapiKey.in: Where the key is located (queryorheader).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:
- Authorization Request: The client application redirects the user to the authorization server (e.g., your
/oauth/authorizeendpoint). - User Consent: The user logs into the authorization server and approves the client application’s request for specific
scopes(permissions). - Authorization Code: The authorization server redirects the user back to the client application with an
authorization code. - Token Request: The client application exchanges the
authorization code(along with itsclient_idandclient_secret) for anaccess tokenat the token endpoint (e.g., your/oauth/token). - Resource Access: The client application uses the
access tokento make requests to your API’s protected resources. Your API validates the token with the authorization server or by checking its signature and expiry.
- Authorization Request: The client application redirects the user to the authorization server (e.g., your
- Levers:
type: Must beoauth2.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(forauthorizationCodeandimplicitflows): The endpoint where users grant consent.scopes: The available permissions the client can request.
- Example Usage:
Note that thesecurity: - oauth2Auth: # Refers to the 'oauth2Auth' scheme - read:Users # Requesting the 'read:Users' scopeoauth2Authscheme itself might be configured with multiple flows (e.g.,clientCredentialsandpassword), and thesecuritysection 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:
- Discovery: The client uses the
openIdConnectUrlto discover the OIDC provider’s endpoints (authorization, token, userinfo, JWKS). - Authentication Request: The client redirects the user to the OIDC provider’s authorization endpoint, requesting an
id_tokenand anaccess_token. - User Authentication & Consent: The user logs into the OIDC provider.
- ID Token & Access Token: The OIDC provider returns an
id_token(a JWT containing user identity claims likesub,name,email) and anaccess_tokento the client. - API Verification: The client sends the
id_tokenoraccess_tokento your API. Your API verifies the token’s signature against the OIDC provider’s public keys (obtained via thejwks_urifrom the discovery document), checks its issuer and audience, and verifies its expiry. Theid_tokenprovides proof of authentication, and theaccess_tokencan be used for authorization.
- Discovery: The client uses the
- Levers:
type: Must beopenIdConnect.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:
When using OIDC, thesecurity: - openIdConnectAuth: [] # Refers to the 'openIdConnectAuth' schemesecuritysection usually just refers to the OIDC scheme. Theid_tokenoraccess_tokenobtained from the OIDC provider is then typically passed in theAuthorization: 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.