JSON Web Token (JWT) — Structure Validation Regex for Python
/^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/What this pattern does
This page provides a well-structured, multi-part regular expression for matching json web token (jwt) — structure validation, ported and verified for Python. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# JSON Web Token (JWT) — Structure Validation
# ReDoS-safe | RegexVault — Security > API Keys & Tokens
import re
json_web_token_jwt_structure_validation_pattern = re.compile(r'^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$')
def validate_json_web_token_jwt_structure_validation(value: str) -> bool:
return bool(json_web_token_jwt_structure_validation_pattern.fullmatch(value))
# Example
print(validate_json_web_token_jwt_structure_validation("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c | eyJhbGci.eyJzdWI.sig.extra |
header.payload.signature | eyJhbGci.eyJzdWI |
aaa.bbb.ccc | not.a.jwt.at.all.here |
| — | a.b. |
When to use this pattern
This pattern is drawn from the Security > API Keys & Tokens category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Never trust a JWT whose signature you have not verified. The 'alg: none' attack bypasses signature verification. Never accept tokens with algorithm 'none'. Validate expiry (exp claim) — expired tokens must be rejected.
Technical Notes
Structure only — does not validate header algorithm, payload claims, expiry, or signature. Three segments: header (base64url) + payload (base64url) + signature (base64url, may be empty for 'none' algorithm — always reject 'none'). Capture groups: 1=header, 2=payload, 3=signature.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern