API Security
π API Security β Authentication, Authorization & Token Handling
βAPIs are the backbone of modern applications β securing them means securing everything.β
π§© Authentication vs Authorization
Authentication
Identifies who is making the request (user or machine)
Authorization
Determines what that entity is allowed to do
β οΈ You canβt perform authorization without authenticating the entity first.
π§ API Authentication Methods
1. Basic Authentication
Uses the
Authorization
HTTP header with theBasic
scheme.Sends
username:password
as Base64 (not encryption).Often used for quick machine or user identity checks.
β Risk: Credentials easily exposed even under TLS.
2. API Keys
Single static token identifying the calling app.
Used for:
Rate limiting / throttling
Monetization / analytics
β Simple to implement
β Limited: identifies app, not user
β Keys often end up hardcoded in source or leaked via logs.
3. mTLS (Mutual TLS)
Both client and server present digital certificates.
Verifies machine identity securely.
β Encrypted, strong machine auth
β Certificate management complexity
β Not suited for end-user auth
4. Token-Based Authentication
Modern, flexible, and secure.
Tokens are issued by an Identity Provider (IdP) and verified by APIs.
Supports:
Expiration and refresh
Audiences and scopes
Embedded claims (user roles, context)
β Enables stateless and scalable API authentication.
π OAuth & OpenID Connect (OIDC)
π OAuth 2.0
A delegation protocol for controlled access to APIs.
Removes the need for apps to handle user credentials.
Core principle: βAccess without password sharing.β
Current: OAuth 2.0 (since 2012)
Upcoming: OAuth 2.1 (cleanup & backward-compatible)
π€ OpenID Connect (OIDC)
Identity layer built on top of OAuth 2.0.
Adds user identity info (e.g., email, profile).
Enables federated login (e.g., Google Sign-In).
Used for SSO β not typically for machine-only APIs.
π§± OAuth Architecture
Resource Owner (RO)
The user who owns the data
Client
The application requesting access
Authorization Server (AS)
Authenticates user and issues tokens
Resource Server (RS)
The API hosting protected resources
Flow Summary:
User authorizes β Client receives token β Client calls API with token
π§© OAuth vs Authorization
OAuth = Delegation, not authorization. The user delegates limited access to an app.
Actual authorization decisions still happen at the API (resource server).
π‘ Analogy: Your boss (resource owner) gives you (client) a signed note (token) to the bank (API). The bank may still deny certain actions β delegation β full access.
π Common OAuth Flows
Authorization Code (with PKCE)
Web & mobile apps
β Yes
β Yes
πππ
Refresh Token
Session renewal
β οΈ Needs valid refresh
β Yes
ππ
Client Credentials
Machine-to-machine
β No
β No
ππ
π 1. Authorization Code Flow (with PKCE)
Best for user-facing web/mobile apps.
Steps:
Client redirects user to
/authorize
(withcode_challenge
)User authenticates β Auth server returns one-time code
Client sends
/token
request withcode_verifier
Server issues Access Token + Refresh Token
β PKCE ensures the code canβt be hijacked.
β»οΈ 2. Refresh Token Flow
Used to obtain new access tokens without re-login.
Long-lived tokens (hoursβmonths).
Rotate refresh tokens where possible.
βοΈ 3. Client Credentials Flow
For backend jobs / cron / microservices.
No user interaction.
Client sends its own credentials to get access token.
Access tokens short-lived; no refresh token.
π Tokens Deep Dive
π¦ Token Formats
By Reference (Opaque)
Random string validated via introspection
Privacy
Requires extra call
By Value (JWT)
Self-contained, signed
Fast, no lookup
Sensitive data risk if leaked
π― Token Purposes
Access Token
Client β API
Grants API access
Refresh Token
Client β Auth Server
Gets new access tokens
ID Token
Client only
Provides identity (OIDC)
π Token Types
Bearer
Cash π΅
Whoever has it can use it
Proof of Possession (PoP)
Credit card + PIN π³
Must prove token ownership (DPoP/mTLS)
π§Ύ JSON Web Tokens (JWT)
Structure:
<Header>.<Payload>.<Signature>
Header: Algorithm (alg
), Key ID (kid
)
Payload: sub
, iss
, aud
, exp
, iat
, scope
, custom claims
Signature: Ensures integrity
πΈ JWS: Signed JWT (common) πΈ JWE: Encrypted JWT (confidential)
β οΈ Security Tips
Reject
alg: none
Validate signature,
exp
,aud
,iss
Donβt decode JWTs on clients
Donβt trust token content without verification
π§ Scopes & Claims
Scope
What an app can do
invoice_read
Claim
Who the user is / attributes
"email": "jacob@example.com"
Scopes = coarse-grained, app-level permissions
Claims = fine-grained, user-level data
π‘ Example:
{
"scope": "invoice_read",
"claims": {
"sub": "jacob123",
"department": "Finance"
}
}
π Best Practices for Scopes & Claims
Keep scopes broad and few (
invoice_read
, notinvoice_read_1
)Use claims for fine-grained resource checks
Include only trusted attributes
Never put sensitive data in claims
Combine both for layered authorization
π API Gateway & Token Validation
Gateway
Validates tokens, checks scopes
API
Evaluates claims for fine-grained access
Flow:
Gateway receives token β validates via
/introspect
or/token_exchange
Gateway passes JWT downstream
API verifies claims and applies access rules
β Zero Trust Ready β every layer validates identity & intent.
π API-to-API Token Strategies
Exchange
Request new token with reduced scopes
Scoped delegation
Embed
Pass downstream tokens inside main token
Controlled service chaining
Share
Reuse token (same trust zone only)
Internal APIs
Last updated