REGEXVAULTv2.0
Security/API Keys & Tokens
Verified Safe

JWT Header (Decoded Algorithm Field) Regex for Python

/^\{"alg":"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)","typ":"JWT"(?:,"kid":"[^"]{1,100}")?\}$/

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching jwt header (decoded algorithm field), 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

Python
# JWT Header (Decoded Algorithm Field)
# ReDoS-safe | RegexVault — Security > API Keys & Tokens

import re

jwt_header_decoded_algorithm_field_pattern = re.compile(r'^\{"alg":"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)","typ":"JWT"(?:,"kid":"[^"]{1,100}")?\}$')

def validate_jwt_header_decoded_algorithm_field(value: str) -> bool:
    return bool(jwt_header_decoded_algorithm_field_pattern.fullmatch(value))

# Example
print(validate_jwt_header_decoded_algorithm_field("{"alg":"HS256","typ":"JWT"}"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
{"alg":"HS256","typ":"JWT"}{"alg":"none","typ":"JWT"}
{"alg":"RS256","typ":"JWT","kid":"key-id-12345"}{"alg":"HS256"}
{"alg":"ES256","typ":"JWT"}{"alg":"RS256","typ":"jwt"}
{"typ":"JWT","alg":"RS256"}

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

The algorithm confusion attack (CVE class) occurs when the verifier is tricked into using a different algorithm than intended. Always specify and enforce the expected algorithm in your verification code — never trust the algorithm from the token header.

Technical Notes

Explicitly excludes 'none' and weak algorithms (HS1, MD5). Approved algorithms: HMAC-SHA (HS256/384/512), RSA PKCS#1 v1.5 (RS*), ECDSA (ES*), RSA-PSS (PS*), EdDSA. The 'kid' (key ID) claim is optional. JSON key order is enforced — real parsers should be order-agnostic.

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