Skip to main content

How to Create a JWT in Go with golang-jwt

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

In Go, the golang-jwt/jwt/v5 package creates JSON Web Tokens in two calls: jwt.NewWithClaims builds a token from a signing method and your claims, and SignedString signs it with a key and returns the token string.

Syntax​

Syntax
token := jwt.NewWithClaims(<signing method>, <claims>)
signed, err := token.SignedString(<key>)
PartWhat it does
<signing method>The algorithm, such as jwt.SigningMethodHS256.
<claims>The claims: a struct that embeds jwt.RegisteredClaims, or a jwt.MapClaims map.
SignedString(<key>)Signs the token and returns it as a string, plus an error. For HS256 the key is a []byte.

From the package documentation: "NewWithClaims creates a new Token with the specified signing method and claims." and "SignedString creates and returns a complete, signed JWT. The token is signed using the SigningMethod specified in the token."

The Example​

The example creates a token for the user ada with the role reader, issued now and valid for 10 minutes, signs it with HS256 and prints it.

The key is 32 random bytes, made with openssl rand -base64 32 and written as base64. It sits in the code only so the example runs as it is. A real application loads its key from configuration, such as an environment variable or a secret store, 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 the package:

Output
go: downloading github.com/golang-jwt/jwt/v5 v5.3.1
go: downloading github.com/golang-jwt/jwt v3.2.2+incompatible
go: added github.com/golang-jwt/jwt/v5 v5.3.1

The second line is Go checking the older module path github.com/golang-jwt/jwt while it works out which module holds the package. Only v5.3.1 is added.

Step 2: Write the Code​

Create main.go:

main.go, which defines Claims with a Role field and the embedded jwt.RegisteredClaims, decodes the base64 key, fills Claims with role reader, subject ada, issued-at now and expiry ten minutes later, signs it with jwt.NewWithClaims, SigningMethodHS256 and SignedString, and prints it.

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() {
// 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("VfosHbT9z3nikPe56UUfKL9Y6mF2oOui09j4GCY0AYs=")
if err != nil {
fail(err)
}

now := time.Now()
claims := Claims{
Role: "reader",
RegisteredClaims: jwt.RegisteredClaims{
Subject: "ada",
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(10 * time.Minute)),
},
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString(key)
if err != nil {
fail(err)
}
fmt.Println(signed)
}

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

jwt.RegisteredClaims holds the standard claims, such as Subject and ExpiresAt, and embedding it gives Claims all of them. jwt.NewNumericDate turns a time.Time into the Unix-seconds form JWTs use.

Step 3: Run It​

Terminal
go run .
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicmVhZGVyIiwic3ViIjoiYWRhIiwiZXhwIjoxNzk1NjgzMTA1LCJpYXQiOjE3OTU2ODI1MDV9.txSf5lXEIpwCA8b-yCGhItbYicsHnQDyibSDCrC5jCA

A zsh terminal where go run . prints a JWT made of three base64url parts separated by dots.

go run . compiles the package in this folder and runs it. Your token will differ, because iat and exp hold the time you run it. Decoded from base64url, the header and payload read:

Header
{"alg":"HS256","typ":"JWT"}
Payload
{"role":"reader","sub":"ada","exp":1795683105,"iat":1795682505}

The JSON keys come from the struct tags: role from the json:"role" tag, and sub, exp and iat from the tags inside jwt.RegisteredClaims.

Common Mistakes​

MistakeWhat happensDo this instead
Passing the key as a stringkey is of invalid type: HMAC sign expects []bytePass a []byte
A short keygolang-jwt signed with a 5-byte key without complaint, but RFC 7518 requires at least 256 bits for HS256Use 32 random bytes or more
Ignoring the error from SignedStringOn an error it returns "", so an empty string goes out as the tokenCheck err

Troubleshooting​

SymptomLikely causeFix
key is of invalid type: HMAC sign expects []byteThe key is a stringConvert or decode it to []byte
A claim is missing from the payloadThe struct field isn't exported: a lowercase role field was left out, and go vet warned struct field role has json tag but is not exportedStart the field name with a capital letter
no required module provides package github.com/golang-jwt/jwt/v5The module wasn't addedRun go get github.com/golang-jwt/jwt/v5

FAQ​

Struct or jwt.MapClaims?​

A struct gives your claims fixed names and types, checked by the compiler. jwt.MapClaims is a map for claims you only know at run time.

How long should the key be?​

At least 32 bytes. RFC 7518, section 3.2: "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm."

Conclusion​

Put your claims in a struct that embeds jwt.RegisteredClaims, call jwt.NewWithClaims(jwt.SigningMethodHS256, claims), and SignedString(key) returns the signed token. Pass the key as 32 or more random bytes.

Additional Resources​