How to Verify a JWT in Go with golang-jwt ParseWithClaims
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
claims := &<ClaimsType>{}
token, err := jwt.ParseWithClaims(<token string>, claims, func(*jwt.Token) (any, error) {
return <key>, nil
}, jwt.WithValidMethods([]string{"<algorithm>"}))
| Part | What it does |
|---|---|
<token string> | The JWT to check. |
claims | A pointer to your claims struct, which ParseWithClaims fills. |
| The key function | Called 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, err | The 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
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:

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
go run .
ada reader
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 wrong | err.Error() | errors.Is with |
|---|---|---|
| Signed with another key, or the payload was changed | token signature is invalid: signature is invalid | jwt.ErrSignatureInvalid |
| The token has expired | token has invalid claims: token is expired | jwt.ErrTokenExpired |
Signed with HS384, but WithValidMethods allows only HS256 | token signature is invalid: signing method HS384 is invalid | |
WithExpirationRequired(), and there's no exp | token has invalid claims: token is missing required claim: exp claim is required | |
| Not a JWT at all | token 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
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out WithValidMethods | The token's header picks the algorithm | Pass jwt.WithValidMethods([]string{"HS256"}) |
The key function returns a string | token signature is invalid: key is of invalid type: HMAC verify expects []byte | Return a []byte |
Using claims when err isn't nil | You'd trust claims from a token that failed | Check err first |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
token signature is invalid: signature is invalid | Another key signed it, or it was changed | Verify with the signing key; reject the token |
token has invalid claims: token is expired | The exp has passed | Get a new token, or add a little WithLeeway |
signing method … is invalid | The token's algorithm isn't in WithValidMethods | Sign 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
- golang-jwt/jwt/v5, on pkg.go.dev.
- RFC 8725: JSON Web Token Best Current Practices, section 3.1, "Perform Algorithm Verification".
