Skip to main content

How to Add Registered Claims to a JWT in Go with jwt.RegisteredClaims

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

golang-jwt has a struct for the seven registered JWT claims, jwt.RegisteredClaims, with a field for each: Issuer, Subject, Audience, IssuedAt, NotBefore, ExpiresAt and ID. It writes aud as an array even for one audience, unless you set jwt.MarshalSingleStringAsArray to false.

Syntax​

Syntax
claims := jwt.RegisteredClaims{
Issuer: "<iss>",
Subject: "<sub>",
Audience: jwt.ClaimStrings{"<aud>"},
IssuedAt: jwt.NewNumericDate(<time.Time>),
NotBefore: jwt.NewNumericDate(<time.Time>),
ExpiresAt: jwt.NewNumericDate(<time.Time>),
ID: "<jti>",
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(<key>)
PartWhat it does
Issuer, Subject, IDWrite iss, sub and jti.
AudienceWrites aud. jwt.ClaimStrings is a list of strings, here with one item.
IssuedAt, NotBefore, ExpiresAtWrite iat, nbf and exp. jwt.NewNumericDate turns a time.Time into whole seconds.
SignedString(<key>)Signs the claims and returns the token.

The golang-jwt source documents NewNumericDate: "It will truncate the timestamp according to the precision specified in TimePrecision", which is a second by default.

The Example​

The example signs a token for a user named ada, issued by https://login.example.org for https://photos.example.org, with iat and nbf set to now, exp two hours later and a random UUID as its ID. It prints the token and its payload, then signs the same claims again after setting jwt.MarshalSingleStringAsArray = false.

Prerequisites​

  • Go 1.27 or later, for the uuid package. 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:

main.go, which fills jwt.RegisteredClaims with Issuer, Subject, Audience as ClaimStrings, IssuedAt and NotBefore now, ExpiresAt two hours later and a uuid.New ID, signs and prints the token and its payload, then sets MarshalSingleStringAsArray to false and prints the payload again.

main.go
package main

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

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

// payloadOf returns a token's payload as JSON text.
func payloadOf(token string) string {
payload, err := base64.RawURLEncoding.DecodeString(strings.Split(token, ".")[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return string(payload)
}

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 {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}

now := time.Now()
claims := jwt.RegisteredClaims{
Issuer: "https://login.example.org",
Subject: "ada",
Audience: jwt.ClaimStrings{"https://photos.example.org"},
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(2 * time.Hour)),
ID: uuid.New().String(),
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(token)
fmt.Println(payloadOf(token))

// Write a single audience as a string instead of an array.
jwt.MarshalSingleStringAsArray = false
token, err = jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(key)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(payloadOf(token))
}

payloadOf decodes the token's middle piece with base64.RawURLEncoding, to show the claims as JSON. uuid.New() comes from Go's standard library.

Step 3: Run It​

Terminal
go run .
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjpbImh0dHBzOi8vcGhvdG9zLmV4YW1wbGUub3JnIl0sImV4cCI6MTc5NjA2NjYzNywibmJmIjoxNzk2MDU5NDM3LCJpYXQiOjE3OTYwNTk0MzcsImp0aSI6IjI5MWQxMGIzLTQ1OWItNGI2MC05NGY0LWVlNmU4YWYzYzA2YyJ9.Hbczviy3cJI9n1u7vJmS9bR2U0dsUWP2on6Iel1Kq-M
{"iss":"https://login.example.org","sub":"ada","aud":["https://photos.example.org"],"exp":1796066637,"nbf":1796059437,"iat":1796059437,"jti":"291d10b3-459b-4b60-94f4-ee6e8af3c06c"}
{"iss":"https://login.example.org","sub":"ada","aud":"https://photos.example.org","exp":1796066637,"nbf":1796059437,"iat":1796059437,"jti":"291d10b3-459b-4b60-94f4-ee6e8af3c06c"}

A zsh terminal where go run prints the token, its payload with aud as an array holding https://photos.example.org, and a second payload where aud is a plain string.

What Happened​

  • The claims came out in the struct's order: iss, sub, aud, exp, nbf, iat, jti. JSON objects have no order that matters, so that's fine.
  • aud was an array in the first payload, ["https://photos.example.org"]. The source explains why: MarshalSingleStringAsArray "If it is set to true (the default), it will always serialize the type as an array of strings, even if it just contains one element".
  • After setting it to false, aud was a plain string. Everything else stayed the same, including the jti.
  • exp is 7200 higher than iat: 2 * time.Hour in seconds.

MarshalSingleStringAsArray is a package variable, so changing it changes every token the program writes afterwards.

Common Mistakes​

MistakeWhat happensDo this instead
Passing a plain string as AudienceIt doesn't compile, because Audience is a ClaimStringsWrite jwt.ClaimStrings{"..."}
Expecting a string audServices that read aud as one string fail on the arraySet jwt.MarshalSingleStringAsArray = false when a reader needs a string
Passing a time.Time to ExpiresAt directlyThe field is a *NumericDate, so it doesn't compileWrap it with jwt.NewNumericDate

Troubleshooting​

SymptomLikely causeFix
cannot use "..." (untyped string constant) as jwt.ClaimStrings value in struct literalA string was given to AudienceUse jwt.ClaimStrings{"..."}
cannot use time.Now() (value of struct type "time".Time) as *jwt.NumericDate value in struct literalA time.Time was given to a time fieldUse jwt.NewNumericDate(...)

FAQ​

How do I add claims of my own?​

Embed jwt.RegisteredClaims in a struct of your own, next to your own fields with json tags. golang-jwt writes both.

Do I have to set all seven claims?​

No. Every field has omitempty in its JSON tag, so a field you leave empty is left out of the token.

Conclusion​

Fill jwt.RegisteredClaims to set the seven claims, wrap times with jwt.NewNumericDate and audiences with jwt.ClaimStrings, and remember that golang-jwt writes aud as an array unless you change MarshalSingleStringAsArray.

Additional Resources​