Brute Force Attack in Fastapi with Jwt Tokens
Brute Force Attack in Fastapi with Jwt Tokens — how this specific combination creates or exposes the vulnerability
A brute force attack against an API using Fastapi and JWT tokens typically targets the authentication endpoint or token validation logic. In this combination, the attacker attempts many token values or credential combinations to discover valid tokens or escalate privileges. Because JWT tokens often contain encoded information and are accepted if signature verification passes or if a weak secret is used, attackers can exploit weak token generation, missing rate limiting, or predictable token values to gain unauthorized access.
Fastapi does not inherently prevent brute force attempts at the HTTP layer; without explicit protections, an endpoint that issues or validates JWT tokens can be hammered with guesses. Common weaknesses include using short or non-random secrets, failing to enforce per-user or per-IP rate limits on login and token verification endpoints, and accepting unsigned tokens (alg: none). Attack patterns such as credential stuffing, token enumeration, or offline dictionary attacks against poorly protected secrets can succeed, leading to account takeover or unauthorized access to protected routes.
In black-box scanning, middleBrick tests authentication, BOLA/IDOR, and rate limiting while analyzing OpenAPI specifications for JWT security definitions. It checks whether token-related endpoints are subject to excessive unauthenticated requests, whether tokens leak sensitive information in error messages, and whether signature verification is consistently enforced. By correlating spec definitions with runtime behavior, the scanner identifies gaps such as missing binding between tokens and client context, lack of token expiration enforcement, or weak cryptographic practices that facilitate brute force attacks.
For example, an endpoint that accepts a JWT in the Authorization header without strict audience or issuer validation may be tricked into trusting a tampered token if the secret is weak. Similarly, an endpoint that reveals different error messages for missing versus invalid tokens can leak information that aids enumeration. MiddleBrick’s checks include input validation, authentication mechanisms, and rate limiting to surface these risks, and findings are mapped to frameworks such as OWASP API Top 10 and relevant compliance controls.
Jwt Tokens-Specific Remediation in Fastapi — concrete code fixes
Remediation focuses on strengthening token generation, verification, and endpoint protections. Use strong secrets, enforce short expirations, bind tokens to client context, and apply strict rate limiting on authentication paths. Below are concrete Fastapi examples that demonstrate secure handling of JWT tokens.
from datetime import datetime, timedelta
from typing import Optional
from fastapi import Fastapi, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import jwt
from jwt import PyJWK, PyJWKClient
SECRET_KEY = "your-strong-secret-here-rotate-regularly"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 15
app = Fastapi()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Helper: create token with explicit claims and short expiry
def create_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire, "iat": datetime.utcnow(), "jti": str(uuid4())})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
# Dependency to verify token and enforce audience/issuer
def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(
token,
SECRET_KEY,
algorithms=[ALGORITHM],
audience="myapi",
issuer="auth-service",
)
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials")
return {"username": username, "scopes": payload.get("scopes", [])}
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired")
except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# Replace with real user validation and password hashing
if form_data.username != "admin" or form_data.password != "correct-horse-battery-staple":
raise HTTPException(status_code=400, detail="Incorrect username or password")
token = create_token(data={"sub": form_data.username, "scopes": ["read", "write"]})
return {"access_token": token, "token_type": "bearer"}
@app.get("/protected")
async def protected_route(current_user: dict = Depends(get_current_user)):
return {"message": f"Hello {current_user['username']}", "scopes": current_user["scopes"]}
To further harden against brute force:
- Enforce rate limiting at the API gateway or within Fastapi using a middleware or third-party library, applying limits per user and per IP on /token and sensitive endpoints.
- Bind tokens to client fingerprints (e.g., a hash of IP + user-agent) and validate this binding on each request where appropriate, reducing the impact of token leakage.
- Use asymmetric algorithms (RS256) with JWKS exposure via PyJWKClient, and validate audience and issuer strictly to prevent token substitution across services.
- Ensure error messages are uniform for authentication failures to avoid information disclosure that could aid enumeration.
middleBrick can validate these practices by scanning your OpenAPI spec for missing security schemes, weak token lifetimes, and inconsistent enforcement, and by testing rate limiting and authentication behavior. With the Pro plan, continuous monitoring and GitHub Action integration can alert you if risk scores degrade after changes, while the MCP Server allows you to initiate scans directly from your IDE.