Go JWT Authentication with Claims

Generate and validate JWT tokens in Go using the golang-jwt package with custom claims, token expiration, and middleware for protected HTTP routes. Includes.

GoAuth Jwt

Code

snippet
package main

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

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

func generateToken(userID string) (string, error) {
  claims := jwt.MapClaims{
    "user_id": userID,
    "exp":     time.Now().Add(24 * time.Hour).Unix(),
  }
  token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  return token.SignedString(secretKey)
}

func validateToken(tokenString string) (jwt.MapClaims, error) {
  token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
    return secretKey, nil
  })
  if err != nil { return nil, err }
  return token.Claims.(jwt.MapClaims), nil
}

Inside the snippet

Go JWT Authentication with Claims keeps everything in the functions generateToken and validateToken.

Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

Points of care

  • Plan for an install step: github.com/golang-jwt/jwt/v5 is a real dependency, resolved by the package manager.
  • error is part of the return tuple, so every caller decides what failure means.

Putting it to use

The primary signature is func generateToken(userID string) (string, error)

Core lines

if err != nil { return nil, err }
func generateToken(userID string) (string, error) {
  claims := jwt.MapClaims{
    "user_id": userID,
    "exp":     time.Now().Add(24 * time.Hour).Unix(),
  }
  token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  return token.SignedString(secretKey)
}
return token.Claims.(jwt.MapClaims), nil

Interactive Tools for This Topic

FAQ

How does the code signal failure?
Through `error` values, not panics — the snippet checks `err != nil` at 1 site.
Which packages must be installed first?
Yes. The imports resolve to `github.com/golang-jwt/jwt/v5`, which the package manager must provide.