Skip to main content

How to Verify a JWT in Go with golang-jwt ParseWithClaims

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

In Go, jwt.ParseWithClaims from golang-jwt/jwt/v5 verifies a JSON Web Token and fills your claims struct with what it says. A key function hands it the key, and options such as jwt.WithValidMethods set the rules. When anything fails, it returns an error that says what.

Syntax​

Syntax
claims := &<ClaimsType>{}
token, err := jwt.ParseWithClaims(<token string>, claims, func(*jwt.Token) (any, error) {
return <key>, nil
}, jwt.WithValidMethods([]string{"<algorithm>"}))
PartWhat it does
<token string>The JWT to check.
claimsA pointer to your claims struct, which ParseWithClaims fills.
The key functionCalled with the parsed token; returns the key to check the signature with. For HS256, the []byte secret.
jwt.WithValidMethods([]string{"<algorithm>"})Accepts only these algorithms, such as "HS256".
token, errThe parsed token, and nil or the reason it failed.

From the package documentation: "ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims interface." On WithValidMethods: "Only those methods will be considered valid. It is heavily encouraged to use this option in order to prevent attacks".

The Example​

The example signs a token for the user ada with the role reader, then parses it twice: with the key that signed it, and with a different key, the way a token from another app would arrive.

Both keys are 32 random bytes, made with openssl rand -base64 32 and written as base64. They sit in the code only so the example runs as it is. A real application loads its key from configuration and never keeps it in the source.

Prerequisites​

  • Go. This guide uses Go 1.27.4.

Step 1: Create the Project​

Terminal
mkdir demo
cd demo
go mod init demo
go get github.com/golang-jwt/jwt/v5

go mod init demo creates a module named demo, and go get adds github.com/golang-jwt/jwt/v5, v5.3.1 here.

Step 2: Write the Code​

Create main.go:

main.go, which signs a token for ada with role reader and a 10-minute expiry, parses it with jwt.ParseWithClaims into a Claims struct with a key function returning the key and WithValidMethods HS256, prints the subject and role, then parses it with another key and prints Rejected with the error.

main.go
package main

import (
"encoding/base64"
"fmt"
"os"
"time"

"github.com/golang-jwt/jwt/v5"
)

// Claims is what the token says: a role plus the registered claims.
type Claims struct {
Role string `json:"role"`
jwt.RegisteredClaims
}

func main() {
// Two keys, 32 random bytes each, written as base64.
// They're in the code only for this example; a real app loads its key from its configuration.
key, err := base64.StdEncoding.DecodeString("VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs=")
if err != nil {
fail(err)
}
otherKey, err := base64.StdEncoding.DecodeString("rAAk7yhJl8rF7vvQeKOeI2ooYrBw9A45aLuMb44gH78=")
if err != nil {
fail(err)
}

signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{
Role: "reader",
RegisteredClaims: jwt.RegisteredClaims{
Subject: "ada",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),
},
}).SignedString(key)
if err != nil {
fail(err)
}

claims := &Claims{}
_, err = jwt.ParseWithClaims(signed, claims, func(*jwt.Token) (any, error) {
return key, nil
}, jwt.WithValidMethods([]string{"HS256"}))
if err != nil {
fail(err)
}
fmt.Println(claims.Subject, claims.Role)

_, err = jwt.ParseWithClaims(signed, &Claims{}, func(*jwt.Token) (any, error) {
return otherKey, nil
}, jwt.WithValidMethods([]string{"HS256"}))
fmt.Println("Rejected:", err)
}

// fail prints an error to standard error and stops the program.
func fail(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

The key function ignores the token it's given and returns one key. The documentation explains why it gets the token at all: "The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as kid) to identify which key to use." claims.Subject comes from the embedded jwt.RegisteredClaims.

Step 3: Run It​

Terminal
go run .
Output
ada reader
Rejected: token signature is invalid: signature is invalid

A zsh terminal where go run . prints ada reader, then Rejected: token signature is invalid: signature is invalid.

go run . compiles the package and runs it. With the right key, ParseWithClaims checked the signature and the expiry and filled claims. With the other key, the signature didn't match, so err said so.

The Errors It Returns​

These came from real runs. Each wraps a sentinel error you can test with errors.Is:

What's wrongerr.Error()errors.Is with
Signed with another key, or the payload was changedtoken signature is invalid: signature is invalidjwt.ErrSignatureInvalid
The token has expiredtoken has invalid claims: token is expiredjwt.ErrTokenExpired
Signed with HS384, but WithValidMethods allows only HS256token signature is invalid: signing method HS384 is invalid
WithExpirationRequired(), and there's no exptoken has invalid claims: token is missing required claim: exp claim is required
Not a JWT at alltoken is malformed: token contains an invalid number of segments

Why WithValidMethods Matters​

Without the option, the same HS384 token parsed with no error, because the key fit that algorithm too. The token chose the algorithm, not your code. Pin it with WithValidMethods.

Leeway and a Required exp​

Two more options cover common needs. jwt.WithLeeway(time.Minute) allows for clock skew: a token that had expired 30 seconds earlier still parsed. jwt.WithExpirationRequired() rejects tokens without exp, which golang-jwt otherwise accepts: "By default exp claim is optional."

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out WithValidMethodsThe token's header picks the algorithmPass jwt.WithValidMethods([]string{"HS256"})
The key function returns a stringtoken signature is invalid: key is of invalid type: HMAC verify expects []byteReturn a []byte
Using claims when err isn't nilYou'd trust claims from a token that failedCheck err first

Troubleshooting​

SymptomLikely causeFix
token signature is invalid: signature is invalidAnother key signed it, or it was changedVerify with the signing key; reject the token
token has invalid claims: token is expiredThe exp has passedGet a new token, or add a little WithLeeway
signing method … is invalidThe token's algorithm isn't in WithValidMethodsSign and verify with the same algorithm

FAQ​

What does ParseWithClaims return besides the error?​

The parsed *jwt.Token. For the valid token, token.Valid was true, token.Method.Alg() was HS256 and token.Header["typ"] was JWT.

Do I need the returned token?​

Not when you pass your own claims struct: ParseWithClaims fills it, so the example ignores the token with _.

Conclusion​

jwt.ParseWithClaims(tokenString, &Claims{}, keyFunc, jwt.WithValidMethods([]string{"HS256"})) verifies the signature, the algorithm and the time claims, and fills your struct only when they pass. Check the error first, and use errors.Is to tell an expired token from a forged one.

Additional Resources​