Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/jwt-tokens/go$ _

Generate JWT Tokens in Go

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Go

What: Generate secure JWT tokens in Go using the golang-jwt library. Idiomatic Go implementation for microservices, REST APIs, and cloud-native authentication.

Try it: Use our interactive Jwt-tokens generator or integrate this code into your Go application.

Generate secure JWT tokens in Go using the golang-jwt library. Idiomatic Go implementation for microservices, REST APIs, and cloud-native authentication. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Ruby or use our interactive web generator.

Go Code Example

package main

import (
    "fmt"
    "time"

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

var secretKey = []byte("your-256-bit-secret-key")

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

func GenerateJWT(userID int, username, role string) (string, error) {
    claims := Claims{
        UserID:   userID,
        Username: username,
        Role:     role,
        RegisteredClaims: jwt.RegisteredClaims{
            Issuer:    "https://yourdomain.com",
            Audience:  jwt.ClaimStrings{"https://yourdomain.com"},
            ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
            IssuedAt:  jwt.NewNumericDate(time.Now()),
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString(secretKey)
}

func ValidateJWT(tokenString string) (*Claims, error) {
    token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
        // Validate signing method
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
        }
        return secretKey, nil
    })

    if err != nil {
        return nil, err
    }

    if claims, ok := token.Claims.(*Claims); ok && token.Valid {
        return claims, nil
    }

    return nil, fmt.Errorf("invalid token")
}

func main() {
    // Generate JWT
    token, err := GenerateJWT(123, "john_doe", "admin")
    if err != nil {
        panic(err)
    }
    fmt.Println("JWT:", token)

    // Validate JWT
    claims, err := ValidateJWT(token)
    if err != nil {
        panic(err)
    }
    fmt.Printf("User: %s (ID: %d)\n", claims.Username, claims.UserID)
}

[EXPLANATION]

The golang-jwt library (formerly dgrijalva/jwt-go) is the standard JWT implementation for Go. It uses type-safe structs for claims and provides strong validation. Always validate the signing method in the key function to prevent algorithm confusion attacks. Use RegisteredClaims for standard JWT claims.

Expected Output

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjpbImh0dHBzOi8veW91cmRvbWFpbi5jb20iXSwiaWF0IjoxNjgwMDAwMDAwLCJleHAiOjE2ODAwMDM2MDB9.signature

Common Use Cases

  • Go microservices authentication
  • Gin/Echo REST API authorization
  • gRPC metadata authentication
  • Kubernetes operator authentication
  • Cloud-native application auth

Important Notes

  • Install: go get github.com/golang-jwt/jwt/v5
  • Always validate signing method to prevent attacks
  • Use RegisteredClaims for standard claims
  • Consider middleware packages: gin-jwt, echo-jwt
  • Use environment variables for secret keys

Try Our Interactive Generator

Don't want to write code? Use our free web-based Jwt-tokens generator with instant results.

TRY JWT-TOKENS GENERATOR →