Integrity Failures in Fastapi with Jwt Tokens
Integrity Failures in Fastapi with Jwt Tokens — how this specific combination creates or exposes the vulnerability
Integrity failures occur when an API fails to verify that data has not been altered in transit or after being processed. In FastAPI applications that rely on JWT tokens for authentication, integrity failures typically arise when the server does not enforce strict token validation, allowing an attacker to tamper with the payload or use a token that lacks proper cryptographic guarantees.
JWTs consist of three parts: header, payload, and signature. The signature is what ensures integrity. If the server only decodes the token without verifying the signature, or if it uses a weak algorithm such as none or asymmetric keys without proper key management, the integrity of the token can be compromised. In FastAPI, this often happens when the developer uses a high-level dependency that automatically decodes the token but skips explicit algorithm and issuer validation.
For example, if a FastAPI route uses a dependency that calls jwt.decode without specifying algorithms or without validating the iss (issuer) and aud (audience) claims, an attacker could supply an unsigned token or a token signed with a different key. This can lead to privilege escalation, unauthorized data access, or bypassing authorization checks. The vulnerability is compounded when the application also trusts token payload data without re-verifying critical claims on each request.
Another common pattern is using symmetric signing keys across services without rotating them. If a secret key is exposed, an attacker can forge tokens with modified roles or permissions, and FastAPI will accept them as valid if signature verification is not strict. The use of public-key asymmetric algorithms (like RS256) mitigates some risk, but only if the public key is pinned and the token’s kid (key ID) is validated to prevent key confusion attacks.
In the context of the OWASP API Top 10, integrity failures map closely to Broken Object Level Authorization (BOLA) and Security Misconfiguration. An attacker may exploit weak JWT validation to tamper with identifiers in the payload, escalating privileges or accessing other users’ resources. Real-world CVEs involving weak JWT implementations have shown how missing algorithm checks can allow none algorithm tokens to be accepted as authenticated.
middleBrick detects these risks as part of its Authentication and BOLA/IDOR checks, highlighting missing signature validation, missing algorithm constraints, and missing claim verification. By combining OpenAPI/Swagger spec analysis with runtime probes, the scanner identifies whether your FastAPI endpoints are validating JWTs with sufficient integrity controls.
Jwt Tokens-Specific Remediation in Fastapi — concrete code fixes
To remediate integrity failures when using JWT tokens in FastAPI, enforce strict token validation on every request. Always specify allowed algorithms, validate standard claims, and avoid accepting unsigned tokens.
Below is a secure FastAPI dependency that decodes and validates a JWT using the PyJWT library. This example uses RS256 with a public key fetched from a trusted endpoint, ensuring that only tokens signed by the expected key are accepted.
from fastapi import Depends, HTTPException, Security, FastAPI
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt
from jwt import PyJWKClient
import httpx
app = FastAPI()
security = HTTPBearer()
# Configuration: replace with your JWKS endpoint
JWKS_URL = "https://your-auth-provider/.well-known/jwks.json"
audience = "your-api-audience"
issuer = "https://your-auth-provider/"
def get_jwks():
with httpx.Client() as client:
response = client.get(JWKS_URL)
response.raise_for_status()
return PyJWKClient(response.json())
def decode_token(token: str):
jwks_client = get_jwks()
signing_key = jwks_client.get_signing_key_from_jwt(token)
if signing_key is None:
raise HTTPException(status_code=401, detail="Unable to find signing key")
try:
payload = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience=audience,
issuer=issuer,
options={"require": ["exp", "iss", "aud"]},
)
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="Invalid token")
def get_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return decode_token(credentials.credentials)
@app.get("/secure-data")
async def read_secure_data(user=Depends(get_current_user)):
return {"message": f"Hello {user.get('sub')}, your role is {user.get('role')}"}
Key remediation practices:
- Always specify
algorithmsinjwt.decodeand avoid defaulting toNoneor["HS256"]only. - Validate
iss,aud, andexpclaims to ensure the token is intended for your service and has not expired. - Use asymmetric algorithms (RS256/ES256) with a JWKS endpoint rather than shared secrets when possible, and validate the signing key via
kid. - Reject tokens signed with the
nonealgorithm by explicitly listing allowed algorithms and not falling back to insecure options. - Rotate signing keys regularly and configure your JWKS client to refresh keys safely.
For applications using HS256 with a secret, ensure the secret is stored securely (e.g., environment variables or secret manager) and is sufficiently complex. Even with HS256, always validate all standard claims and specify the exact algorithm string.
middleBrick’s CLI can be used to scan your FastAPI endpoints and verify that JWT validation is correctly configured. Run middlebrick scan <your-api-url> to get a security risk score and findings related to authentication integrity.
Frequently Asked Questions
What should I do if my FastAPI app currently decodes JWTs without specifying algorithms?
algorithms=["RS256"] (or your specific algorithm), and validate iss, aud, and exp. Remove any fallback to the none algorithm and avoid decoding without verification.Can using public-key algorithms like RS256 fully prevent integrity failures with JWTs in FastAPI?
kid to prevent key confusion, and enforce strict claim validation. Asymmetric keys help, but implementation errors can still lead to integrity issues.