Checking JWT validation errors

suggest change
// Token from another example.  This token is expired
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
    return []byte("AllYourBase"), nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))

if token.Valid {
    fmt.Println("You look nice today")
} else if errors.Is(err, jwt.ErrTokenMalformed) {
    fmt.Println("That's not even a token")
} else if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) {
    fmt.Println("Timing is everything")
} else {
    fmt.Println("Couldn't handle this token:", err)
}
Timing is everything

Version 5 exposes sentinel errors for use with errors.Is; the old validation error bit field no longer exists. Treat token.Valid as authoritative: an error may describe an expired token while also wrapping a signature error.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents