Skip to main content

How to Add Custom Claims to a JWT in Go with golang-jwt

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

golang-jwt writes your own claims from a struct: give each field a json tag with the claim's name, embed jwt.RegisteredClaims for iss, sub, aud and exp, and sign the struct with jwt.NewWithClaims. A string field becomes a JSON string, a slice an array and a struct an object, and jwt.ParseWithClaims fills the same struct back from a verified token.

Syntax​

Syntax
type <ClaimsType> struct {
<Field> <type> `json:"<claim name>"`
jwt.RegisteredClaims
}

claims := <ClaimsType>{<Field>: <value>, RegisteredClaims: jwt.RegisteredClaims{ /* iss, sub, aud, exp */ }}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(<key>)
PartWhat it does
<ClaimsType>Your claims struct, such as PhotoClaims.
<Field> <type>One field per custom claim. Its name must start with a capital letter, and its type sets the claim's JSON type: a string becomes a string, a slice an array and a struct an object.
`json:"<claim name>"`The claim's name in the token. Any text works, a URL included.
jwt.RegisteredClaimsEmbedded, so the struct also has Issuer, Subject, Audience, ExpiresAt and the other registered claims, and golang-jwt can check them.
<key>The signing key, here 32 random bytes for HS256.

The golang-jwt documentation for RegisteredClaims: "This type can be used on its own, but then additional private and public claims embedded in the JWT will not be parsed." Its example of a custom claims type adds: "The RegisteredClaims is embedded in the custom type to allow for easy encoding, parsing and validation of registered claims."

The Example​

The example signs a token for a user named Ada, issued by https://login.example.org for https://photos.example.org, that expires in an hour. It has three custom claims of three JSON types: name, a string; roles, a slice of strings; and https://photos.example.org/quota, a Quota struct with an album limit and a storage limit. The last one has a URL as its name, so that no other service's claim can have the same name. The example prints the token and its payload, then verifies the token into a new PhotoClaims and prints three of its values.

Prerequisites​

  • Go. This guide uses Go 1.27.4.

Step 1: Create the Project​

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

go mod init creates the module, and go get adds golang-jwt, version 5.4.0 here.

Step 2: Write the Code​

Create main.go in the demo folder:

main.go, which declares a Quota struct and a PhotoClaims struct with name, roles and a quota field tagged https://photos.example.org/quota plus the embedded jwt.RegisteredClaims, signs Ada's claims with HS256, prints the token and its decoded payload, then verifies the token with ParseWithClaims and prints the name, the roles and the album limit.

main.go
package main

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

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

// Quota is the value of the quota claim: a JSON object.
type Quota struct {
Albums int `json:"albums"`
StorageGB int `json:"storage_gb"`
}

// PhotoClaims is the token's payload: the custom claims, plus the registered ones from jwt.RegisteredClaims.
type PhotoClaims struct {
Name string `json:"name"` // a string
Roles []string `json:"roles"` // an array
Quota Quota `json:"https://photos.example.org/quota"` // an object
jwt.RegisteredClaims
}

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

func main() {
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
key, err := base64.StdEncoding.DecodeString("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=")
if err != nil {
fail(err)
}

claims := PhotoClaims{
Name: "Ada",
Roles: []string{"editor", "viewer"},
Quota: Quota{Albums: 10, StorageGB: 50},
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "https://login.example.org",
Subject: "ada",
Audience: jwt.ClaimStrings{"https://photos.example.org"},
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
if err != nil {
fail(err)
}
fmt.Println(token)

// The payload is the token's middle piece, base64url-encoded JSON.
payload, err := base64.RawURLEncoding.DecodeString(strings.Split(token, ".")[1])
if err != nil {
fail(err)
}
fmt.Println(string(payload))

verified := &PhotoClaims{}
_, err = jwt.ParseWithClaims(token, verified, func(*jwt.Token) (any, error) {
return key, nil
},
jwt.WithValidMethods([]string{"HS256"}),
jwt.WithIssuer("https://login.example.org"),
jwt.WithAudience("https://photos.example.org"),
)
if err != nil {
fail(err)
}
fmt.Println(verified.Name, verified.Roles, verified.Quota.Albums)
}
  • PhotoClaims has one field per custom claim, each with its claim name in a json tag, and embeds jwt.RegisteredClaims for the registered claims.
  • Quota is the value of the quota claim. Its fields' tags become the keys of the JSON object.
  • The payload lines take the token's middle piece and decode it with base64.RawURLEncoding, to show the claims as JSON.
  • jwt.ParseWithClaims checks the signature, the algorithm, the expiry, the issuer and the audience, and fills verified with the token's claims.

Step 3: Run It​

In the demo folder:

Terminal
go run .
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQWRhIiwicm9sZXMiOlsiZWRpdG9yIiwidmlld2VyIl0sImh0dHBzOi8vcGhvdG9zLmV4YW1wbGUub3JnL3F1b3RhIjp7ImFsYnVtcyI6MTAsInN0b3JhZ2VfZ2IiOjUwfSwiaXNzIjoiaHR0cHM6Ly9sb2dpbi5leGFtcGxlLm9yZyIsInN1YiI6ImFkYSIsImF1ZCI6WyJodHRwczovL3Bob3Rvcy5leGFtcGxlLm9yZyJdLCJleHAiOjE3OTYyOTY0MjB9.I3wpAkUMPBv1g3dGz0OIyhIlEHYGHyFAxy3a6pq5iFQ
{"name":"Ada","roles":["editor","viewer"],"https://photos.example.org/quota":{"albums":10,"storage_gb":50},"iss":"https://login.example.org","sub":"ada","aud":["https://photos.example.org"],"exp":1796296420}
Ada [editor viewer] 10

A zsh terminal where go run prints the token, then its payload with name Ada, roles editor and viewer as an array, the quota object with albums 10 and storage_gb 50, then iss, sub, aud and exp, and finally Ada, the roles in brackets and 10.

go run . builds and runs the module in the current folder. The command is the same in zsh, bash and PowerShell.

What Happened​

  • The custom claims come first in the payload, in the struct's field order, followed by the registered ones from the embedded jwt.RegisteredClaims: name, roles, the quota, iss, sub, aud, exp. JSON objects have no order that matters, so that's fine.
  • Each field kept its JSON type. "name":"Ada" is a string, "roles":["editor","viewer"] an array, and the quota an object, {"albums":10,"storage_gb":50}, whose keys come from Quota's tags.
  • ParseWithClaims filled a new PhotoClaims from the verified token. Ada [editor viewer] 10 is its name, its roles and its quota's album limit.

I checked other cases too, with golang-jwt 5.4.0:

  • A claim missing from the token doesn't make ParseWithClaims fail. Its field keeps its zero value: for a token with only sub, the name was "", the roles a nil slice and a *Quota field nil, with no error.
  • A claim of the wrong JSON type does. A token with "roles":"customer" gave token is malformed: could not JSON decode claim: json: cannot unmarshal string into Go struct field Claims.roles of type []string.
  • A custom field with a registered claim's name replaces the registered claim. With Sub tagged json:"sub" and set to custom, and Subject set to ada, the payload was {"sub":"custom"}.

Common Mistakes​

MistakeWhat happensDo this instead
A field without a json tagThe claim is named after the field, capital letter included: {"Name":"Ada"}Tag every field with its claim name
A field whose name starts with a lowercase letterIt's left out of the token, because encoding/json writes only exported fieldsCapitalize the field, and set the claim name in its tag
Leaving out jwt.RegisteredClaimsIt doesn't compile: does not implement jwt.Claims (missing method GetAudience)Embed jwt.RegisteredClaims in the struct
Naming a custom claim like a registered one, as in json:"sub"It replaces the registered claimGive custom claims names of their own, such as a URL
A struct claim that may be emptyA struct value is always written: {"quota":{"albums":0}}Make the field a pointer and add omitempty, so a nil quota leaves the claim out

Troubleshooting​

SymptomLikely causeFix
token is malformed: could not JSON decode claim: json: cannot unmarshal string into Go struct field Claims.roles of type []stringA claim in the token has a different JSON type from its fieldMatch the field's type to the claim
cannot use NoRegistered{…} (value of struct type NoRegistered) as jwt.Claims value in argument to jwt.NewWithClaimsThe struct doesn't embed jwt.RegisteredClaimsEmbed it
A field is empty after ParseWithClaims, with no errorThe token doesn't have that claim, or the tag's name differs from the token'sCompare the tag with the claim names in the payload

FAQ​

Can I read custom claims without a struct?​

Yes, with jwt.MapClaims, which the documentation describes as "a claims type that uses the map[string]any for JSON decoding". Numbers come back as float64: a claim of 10 read with MapClaims had the type float64. A struct gives you typed fields instead.

Why does one claim have a URL as its name?​

Short names like quota can collide with another service's claim of the same name. The JWT standard, RFC 7519, says a new claim name should either be registered with IANA or be collision-resistant, and it names domain names as one way to make it so. A URL on a domain you control is such a name.

Conclusion​

Put each custom claim in a struct field with a json tag, embed jwt.RegisteredClaims, and sign the struct with jwt.NewWithClaims. ParseWithClaims fills the same struct from a verified token. A missing claim isn't an error, so check that a claim you need isn't empty before you use it.

Additional Resources​