Phishing Api Keys in Fastapi with Jwt Tokens
Phishing API Keys in FastAPI with JWT Tokens — how this specific combination creates or exposes the vulnerability
When API keys are handled alongside JWT tokens in a FastAPI application, phishing risks increase because both credential types can be inadvertently exposed through logging, error messages, or client-side storage. A common pattern developers use is storing a static API key as an environment variable and also issuing JWTs for user sessions. If the API key is embedded in error responses or debug output, it can be harvested by phishing pages that masquerade as legitimate authentication or analytics endpoints.
Attackers may craft URLs that look like internal FastAPI routes (e.g., /api/v1/auth/token) and trick users or backend services into sending credentials. With JWT tokens, if the signing secret or a poorly configured algorithm (such as none) is discoverable, an attacker can forge tokens. In FastAPI, if the application does not strictly validate the aud (audience) and iss (issuer) claims, a phishing site that obtains a token intended for another audience can reuse it across services.
Phishing can also occur at the infrastructure level: if FastAPI OpenAPI specs are publicly exposed, an attacker can enumerate endpoints that accept API keys and JWTs. The combination means a phished API key might grant access to administrative routes that issue or introspect JWTs, compounding the impact. For example, an endpoint that rotates keys or revokes tokens could be invoked with a phished key, allowing an attacker to disrupt authentication for all users.
Additionally, if FastAPI relies on JWT access tokens but does not enforce strict referrer or origin checks, malicious sites can trick authenticated users into making cross-origin requests that include cookies or bearer tokens. While FastAPI itself does not set cookies by default when using JWTs, middleware or custom wrappers might inadvertently expose headers that include key material in logs or to browser JavaScript, creating a phishing surface.
JWT Tokens-Specific Remediation in Fastapi — concrete code fixes
Secure JWT handling in FastAPI requires strict validation of token structure, claims, and cryptographic parameters. Use the python-jose library with explicit algorithms and audience/issuer checks. Below is a robust example that avoids common pitfalls such as accepting none and skipping verification.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import JWTError, jwt
from pydantic import BaseModel
import os
app = FastAPI()
security_scheme = HTTPBearer()
SECRET_KEY = os.getenv('JWT_SECRET_KEY')
ALGORITHM = 'RS256'
AUDIENCE = 'myapi.example.com'
ISSUER = 'auth.example.com'
class TokenData(BaseModel):
sub: str
scopes: list[str]
def decode_token(token: str) -> TokenData:
try:
payload = jwt.decode(
token,
key=SECRET_KEY,
algorithms=[ALGORITHM],
audience=AUDIENCE,
issuer=ISSUER,
)
return TokenData(sub=payload.get('sub'), scopes=payload.get('scopes', []))
except JWTError as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f'Invalid authentication credentials: {e}',
headers={'WWW-Authenticate': 'Bearer'},
)
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security_scheme)) -> TokenData:
return decode_token(credentials.credentials)
@app.get('/users/me')
def read_current_user(user: TokenData = Depends(get_current_user)):
return {'user_id': user.sub, 'scopes': user.scopes}
Key remediation points: enforce a strong algorithm like RS256 or ES256 instead of HS256 where feasible, always specify audience and issuer, and avoid logging raw tokens. For API keys, store them in a secrets manager and rotate them regularly; do not embed them in JavaScript or client-side code that can be phished. If you use the middleBrick CLI (middlebrick scan <url>), it can detect missing audience/issuer validation and weak algorithms as part of its authentication checks.
In production, serve FastAPI behind a gateway that enforces mutual TLS for sensitive endpoints and strips unnecessary headers before responses reach the application. Middleware that adds security headers and suppresses detailed errors reduces the chance that API keys or JWT metadata leak via phishing-friendly error pages. The Pro plan of middleBrick includes continuous monitoring and GitHub Action integration to ensure these controls remain enforced across deployments.