Security Schemes — Authentication and Authorization in OpenAPI
In this tutorial, you will learn about Security Schemes. We cover key concepts, practical examples, and best practices to help you master this topic.
OpenAPI security schemes define how clients authenticate to your API, supporting API keys, HTTP authentication (Bearer, Basic), OAuth2 flows (authorization code, client credentials, implicit, password), and Openid Connect discovery.
What You'll Learn
You will learn each security scheme type, how to define them in components, how to apply them globally and per-operation, and best practices for documenting authentication.
flowchart LR A[Security Schemes] --> B[API Key] A --> C[HTTP Auth] A --> D[OAuth2] A --> E[OpenID] B:::current classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
Security Scheme Types
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.dodatech.com/oauth/authorize
tokenUrl: https://auth.dodatech.com/oauth/token
scopes:
read:users: Read user data
write:users: Write user data
OpenID:
type: openIdConnect
openIdConnectUrl: https://auth.dodatech.com/.well-known/openid-configuration
Applying Security
# Global security
security:
- BearerAuth: []
# Per-operation override
paths:
/health:
get:
security: [] # Public endpoint
/users:
get:
security:
- BearerAuth: [read:users]
Common Mistakes
- Missing scheme definitions — Referencing undefined schemes.
- No public endpoint marking — Forgetting security: [] for public endpoints.
- Missing scope documentation — Not describing OAuth2 scopes.
- No token endpoint docs — Not showing how to obtain tokens.
Practice Questions
- What are the four security scheme types?
- How do you apply global security?
- How do you make an endpoint public?
- What is the purpose of OAuth2 scopes?
- How does OpenID Connect differ from OAuth2?
Challenge
Design security for a multi-tenant SaaS API with API key auth for server-to-server, Bearer JWT for user sessions, OAuth2 for third-party integrations, and scopes for read/write/admin. Document the login endpoint.
What's Next
In the next lesson, you will learn about tags and external documentation.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro