Regex for JWT Token Detection — Header.Payload.Signature
Regex for detecting JSON Web Tokens (JWTs) in headers, logs, and source code. Matches the three Base64URL segments separated by dots.
Detailed Explanation
Regex for JWT Token Detection
A JWT (RFC 7519) consists of three Base64URL-encoded segments separated by dots: header, payload, and signature. Each segment uses the URL-safe alphabet (A–Z, a–z, 0–9, -, _) with no padding.
Standard JWT Pattern
^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$
Note that the third segment can be empty for unsigned (alg: none) tokens.
Strict Pattern (header must look like JWT JSON)
A signed JWT header always begins with {"alg", which Base64URL-encodes to a string starting with eyJ:
^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$
Match Inside Authorization Header
Bearer\s+(eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)
The capture group extracts the bare token.
Tested Examples
| Input | Standard | Strict |
|---|---|---|
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U |
yes | yes |
eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0. |
yes | yes (empty signature) |
abc.def.ghi |
yes | no (header does not start with eyJ) |
onlyone.twoparts |
no | no |
token: eyJ… |
no | no (extra prefix) |
Useful Caveat
Matching a JWT does not validate it. After detection, use a library (jsonwebtoken, jose) to verify the signature and decode claims. Regex is only for finding tokens in logs, headers, or source code.
Security Note: Log Scrubbing
JWTs frequently end up in access logs, especially on misconfigured load balancers. Use this regex to scan log files for accidental token exposure and rotate any tokens that appear in shared logs.
Use Case
Scanning Git history or log files for accidentally committed JWTs, extracting tokens from `Authorization: Bearer` headers in HAR files, or building a redaction filter for shared debug output.