DevToolsForYou

JWT Encoder and Decoder in Go — Code Examples

JWT Encoder and Decoder in GoUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

The golang-jwt/jwt package is the maintained fork of the popular dgrijalva/jwt-go library. Define a custom Claims struct for typed access.

Go
// go get github.com/golang-jwt/jwt/v5
package main

import (
    "fmt"
    "time"
    "github.com/golang-jwt/jwt/v5"
)

var secret = []byte("my-secret-key")

type Claims struct {
    UserID int    `json:"user_id"`
    Name   string `json:"name"`
    Role   string `json:"role"`
    jwt.RegisteredClaims
}

func main() {
    // Sign (encode)
    claims := Claims{
        UserID: 42, Name: "Alice", Role: "admin",
        RegisteredClaims: jwt.RegisteredClaims{
            ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
            IssuedAt:  jwt.NewNumericDate(time.Now()),
        },
    }
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenStr, err := token.SignedString(secret)
    if err != nil { panic(err) }
    fmt.Println(tokenStr)

    // Verify and decode
    parsed, err := jwt.ParseWithClaims(tokenStr, &Claims{},
        func(t *jwt.Token) (interface{}, error) {
            if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
                return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
            }
            return secret, nil
        })
    if err != nil { panic(err) }
    if c, ok := parsed.Claims.(*Claims); ok {
        fmt.Println(c.Name)   // Alice
        fmt.Println(c.UserID) // 42
    }
}
Notes & gotchas
  • Always validate t.Method in the key function to prevent algorithm switching attacks.
  • jwt.RegisteredClaims embeds standard claims (exp, iat, iss, sub, etc.) — embed it in your custom Claims struct.
  • Use RS256 with crypto/rsa keys for public/private key signing in production environments.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages