> For the complete documentation index, see [llms.txt](https://aashraymt.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aashraymt.gitbook.io/docs/apisec/api-security.md).

# API Security

## &#x20;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:

```json
{
  "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               |
