OpenAPI Security — Defining Authentication and Authorization
In this tutorial, you will learn about OpenAPI Security. We cover key concepts, practical examples, and best practices to help you master this topic.
OpenAPI security defines how clients authenticate to an API using security schemes like API keys, HTTP authentication, OAuth2 flows, and Openid Connect.
What You'll Learn
- Defining security schemes in components
- Applying security globally vs per-operation
- OAuth2 flow types and scopes
Why It Matters
Security definitions ensure clients know how to authenticate and which permissions they need. Missing security specs lead to auth errors.
Code Examples
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
BasicAuth:
type: http
scheme: basic
OAuth2:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://auth.example.com/authorize
tokenUrl: https://auth.example.com/token
scopes:
read: Read data
write: Write data
admin: Admin access
clientCredentials:
tokenUrl: https://auth.example.com/token
scopes:
read: Read data
OpenID:
type: openIdConnect
openIdConnectUrl: https://auth.example.com/.well-known/openid-configuration
# Global security
security:
- BearerAuth: []
paths:
/admin/users:
get:
summary: List all users (admin only)
security:
- BearerAuth: [admin]
responses:
"200":
description: OK
/public/health:
get:
summary: Health check (no auth)
security: []
responses:
"200":
description: OK
Common Mistakes
1. Not Defining Security at All
Every non-public endpoint should have security defined.
2. Using Security Schemes Incorrectly
Match the scheme type to your actual auth implementation.
3. Forgetting to Override Security for Public Endpoints
Set security: [] for public endpoints to override global security.
4. Missing OAuth2 Scopes
Define scopes and specify which operations require which scopes.
5. Overly Complex Security Definitions
Start with simple API key or bearer auth. Add OAuth2 when needed.
Practice Questions
- What are the main security scheme types in OpenAPI?
- Where are security schemes defined?
- How do you apply security globally?
- How do you make an endpoint public (no auth)?
- What is the purpose of OAuth2 scopes?
Answers:
- apiKey, http, oauth2, openIdConnect.
- In
components/securitySchemes. - Using
securityat the top level of the spec. - Set
security: []on the operation. - Scopes define specific permissions within an OAuth2 flow.
Challenge: Define security for a multi-role API with public endpoints, user-level endpoints (read profile, update profile), and admin endpoints.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro