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.
Code
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/v5is a real dependency, resolved by the package manager. erroris 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.OAuth 2.0 PKCE Code GeneratorGenerate RFC 7636 OAuth 2.0 PKCE code verifiers with Web Crypto CSPRNG, compute SHA-256 code challenges, and build full authorization URLs.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.