JSON Web Token (JWT) — Structure Validation Regex for Go
/^([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 Go. 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 Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// JSON Web Token (JWT) — Structure Validation
// ReDoS-safe | RegexVault — Security > API Keys & Tokens
package validation
import "regexp"
var jsonWebTokenJwtStructureValidationRe = regexp.MustCompile(`^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$`)
func ValidateJsonWebTokenJwtStructureValidation(s string) bool {
return jsonWebTokenJwtStructureValidationRe.MatchString(s)
}
// Example
// fmt.Println(ValidateJsonWebTokenJwtStructureValidation("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 Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. 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