API Security

πŸ” API Security β€” Authentication, Authorization & Token Handling

β€œAPIs are the backbone of modern applications β€” securing them means securing everything.”


🧩 Authentication vs Authorization

Concept
Meaning

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 the Basic 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

Actor
Description

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

Flow
Use Case
Involves User
Refresh Token
Security

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:

  1. Client redirects user to /authorize (with code_challenge)

  2. User authenticates β†’ Auth server returns one-time code

  3. Client sends /token request with code_verifier

  4. 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

Type
Description
Pros
Cons

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

Token
Used By
Purpose

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

Type
Analogy
Description

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

Concept
Description
Example

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, not invoice_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

Component
Role

Gateway

Validates tokens, checks scopes

API

Evaluates claims for fine-grained access

Flow:

  1. Gateway receives token β†’ validates via /introspect or /token_exchange

  2. Gateway passes JWT downstream

  3. API verifies claims and applies access rules

βœ… Zero Trust Ready β€” every layer validates identity & intent.


πŸ” API-to-API Token Strategies

Method
Description
Use Case

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