jwt

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

JWT Package

A simple and efficient JWT token management library for Go applications.

Basic Usage

import "your-project/security/jwt"

// Create token manager
tm := jwt.NewTokenManager("your-secret-key")

// With custom configuration
config := &jwt.TokenConfig{
    AccessTokenExpiry:   2 * time.Hour,
    RefreshTokenExpiry:  7 * 24 * time.Hour,
    RegisterTokenExpiry: 30 * time.Minute,
}
tm := jwt.NewTokenManager("secret", config)

Token Generation

payload := map[string]any{"username": "john", "role": "admin"}

// Generate tokens
accessToken, err := tm.GenerateAccessToken("user-123", payload)
refreshToken, err := tm.GenerateRefreshToken("user-123", payload)
registerToken, err := tm.GenerateRegisterToken("user-123", payload, "register")

// With custom expiry
customConfig := &jwt.TokenConfig{Expiry: 1 * time.Hour}
token, err := tm.GenerateAccessToken("user-123", payload, customConfig)

Token Validation & Decoding

// Validate token
token, err := tm.ValidateToken(tokenString)

// Decode claims
claims, err := tm.DecodeToken(tokenString)

// Get payload only
payload, err := tm.GetPayload(tokenString)

// Check expiry
expired := tm.IsTokenExpired(tokenString)
expiryTime, err := tm.GetTokenExpiry(tokenString)

Token Refresh

// Refresh if needed (refresh when < 30 minutes remaining)
newToken, refreshed, err := tm.RefreshTokenIfNeeded(tokenString, 30*time.Minute)
if refreshed {
    // Use new token
}

Configuration Methods

tm.SetSecret("new-secret")
secret := tm.GetSecret()
tm.SetAccessTokenExpiry(3 * time.Hour)
tm.SetRefreshTokenExpiry(14 * 24 * time.Hour)
tm.SetRegisterTokenExpiry(1 * time.Hour)

Claim Extraction Utilities

// Standard claims
tokenID := jwt.GetTokenID(claims)
subject := jwt.GetSubject(claims)
issuer := jwt.GetIssuer(claims)
audience := jwt.GetAudience(claims)
expiry := jwt.GetExpiration(claims)
issuedAt := jwt.GetIssuedAt(claims)
notBefore := jwt.GetNotBefore(claims)

// Payload extraction
payload := jwt.GetPayload(claims)
username := jwt.GetPayloadString(claims, "username")
isAdmin := jwt.GetPayloadBool(claims, "admin")
level := jwt.GetPayloadInt(claims, "level")
roles := jwt.GetPayloadStringSlice(claims, "roles")
hasKey := jwt.HasPayloadValue(claims, "key")

// Safe type extraction
str := jwt.GetString(data, "key")
num := jwt.GetInt(data, "key")
flag := jwt.GetBool(data, "key")
slice := jwt.GetStringSlice(data, "key")
nested := jwt.GetMap(data, "key")

Token Type Validation

isAccess := jwt.IsAccessToken(claims)
isRefresh := jwt.IsRefreshToken(claims)

// Validate specific type
err := jwt.ValidateTokenType(claims, "access")

Token Timing Validation

// Check all timing constraints
err := jwt.ValidateTokenTiming(claims)

// Individual checks
expired := jwt.IsTokenExpired(claims)
active := jwt.IsTokenActive(claims)
stale := jwt.IsTokenStale(claims, 24*time.Hour)

Utility Functions

// Check slice membership
contains := jwt.ContainsValue(slice, "value")
containsAny := jwt.ContainsAnyValue(slice, "val1", "val2")

Documentation

Overview

jwt.go

Index

Constants

View Source
const (
	DefaultAccessTokenExpire   = 2 * time.Hour      // 2 hours
	DefaultRefreshTokenExpire  = 7 * 24 * time.Hour // 7 days
	DefaultRegisterTokenExpire = 30 * time.Minute   // 30 minutes
)

Default token expiration constants

View Source
const (
	ErrNeedTokenProvider = TokenError("token provider required")
	ErrInvalidToken      = TokenError("invalid token")
	ErrTokenExpired      = TokenError("token expired")
	ErrTokenParsing      = TokenError("token parsing error")
)

Error constants

Variables

ProviderSet is the wire provider set for the jwt package. It provides *TokenManager for JWT operations.

Usage:

wire.Build(
    jwt.ProviderSet,
    // ... other providers
)

Functions

func ContainsAnyValue

func ContainsAnyValue(slice []string, values ...string) bool

ContainsAnyValue checks if a slice contains any of the specified values

func ContainsValue

func ContainsValue(slice []string, value string) bool

ContainsValue checks if a slice contains a specific value

func GetAudience

func GetAudience(claims map[string]any) []string

GetAudience extracts audience (aud) from token claims

func GetBool

func GetBool(data map[string]any, key string) bool

GetBool safely extracts boolean value from any map

func GetExpiration

func GetExpiration(claims map[string]any) time.Time

GetExpiration extracts expiration time from token claims

func GetFloat64

func GetFloat64(data map[string]any, key string) float64

GetFloat64 safely extracts float64 value from any map

func GetInt

func GetInt(data map[string]any, key string) int

GetInt safely extracts int value from any map

func GetInt64

func GetInt64(data map[string]any, key string) int64

GetInt64 safely extracts int64 value from any map

func GetIssuedAt

func GetIssuedAt(claims map[string]any) time.Time

GetIssuedAt extracts issued at time from token claims

func GetIssuer

func GetIssuer(claims map[string]any) string

GetIssuer extracts issuer (iss) from token claims

func GetMap

func GetMap(data map[string]any, key string) map[string]any

GetMap safely extracts nested map from any map

func GetNotBefore

func GetNotBefore(claims map[string]any) time.Time

GetNotBefore extracts not before time from token claims

func GetPayload

func GetPayload(claims map[string]any) map[string]any

GetPayload extracts payload from token claims

func GetPayloadBool

func GetPayloadBool(claims map[string]any, key string) bool

GetPayloadBool extracts boolean value from payload

func GetPayloadInt

func GetPayloadInt(claims map[string]any, key string) int

GetPayloadInt extracts int value from payload

func GetPayloadString

func GetPayloadString(claims map[string]any, key string) string

GetPayloadString extracts string value from payload

func GetPayloadStringSlice

func GetPayloadStringSlice(claims map[string]any, key string) []string

GetPayloadStringSlice extracts string slice from payload

func GetString

func GetString(data map[string]any, key string) string

GetString safely extracts string value from any map

func GetStringSlice

func GetStringSlice(data map[string]any, key string) []string

GetStringSlice safely extracts string slice from any map

func GetSubject

func GetSubject(claims map[string]any) string

GetSubject extracts subject (sub) from token claims

func GetTokenID

func GetTokenID(claims map[string]any) string

GetTokenID extracts JWT ID (jti) from token claims

func HasPayloadValue

func HasPayloadValue(claims map[string]any, key string) bool

HasPayloadValue checks if payload contains a specific key with non-empty value

func IsAccessToken

func IsAccessToken(claims map[string]any) bool

IsAccessToken checks if token is an access token

func IsRefreshToken

func IsRefreshToken(claims map[string]any) bool

IsRefreshToken checks if token is a refresh token

func IsTokenActive

func IsTokenActive(claims map[string]any) bool

IsTokenActive checks if token is currently active (not before current time)

func IsTokenExpired

func IsTokenExpired(claims map[string]any) bool

IsTokenExpired checks if token is expired based on claims

func IsTokenStale

func IsTokenStale(claims map[string]any, staleDuration time.Duration) bool

IsTokenStale checks if token is older than specified duration

func ValidateTokenTiming

func ValidateTokenTiming(claims map[string]any) error

ValidateTokenTiming validates token timing (exp, iat, nbf)

func ValidateTokenType

func ValidateTokenType(claims map[string]any, expectedType string) error

ValidateTokenType ensures token is of expected type

Types

type Config added in v0.2.0

type Config struct {
	Secret              string
	AccessTokenExpiry   string
	RefreshTokenExpiry  string
	RegisterTokenExpiry string
}

Config represents JWT configuration for Wire injection. This is used to configure the TokenManager via dependency injection.

type TokenConfig

type TokenConfig struct {
	// For TokenManager configuration
	AccessTokenExpiry   time.Duration
	RefreshTokenExpiry  time.Duration
	RegisterTokenExpiry time.Duration

	// For individual token generation
	Expiry time.Duration
}

TokenConfig represents token configuration options

type TokenError

type TokenError string

TokenError represents JWT token related errors

func (TokenError) Error

func (e TokenError) Error() string

type TokenManager

type TokenManager struct {
	// contains filtered or unexported fields
}

TokenManager handles JWT token operations

func NewTokenManager

func NewTokenManager(secret string, configs ...*TokenConfig) *TokenManager

NewTokenManager creates a new TokenManager instance with optional configuration

func ProvideTokenManager added in v0.2.0

func ProvideTokenManager(cfg *Config) *TokenManager

ProvideTokenManager creates a new TokenManager from configuration. The secret is required; other settings use defaults if not specified.

func ProvideTokenManagerFromSecret added in v0.2.0

func ProvideTokenManagerFromSecret(secret string) *TokenManager

ProvideTokenManagerFromSecret creates a TokenManager directly from a secret string. This is a convenience provider for simple use cases.

func (*TokenManager) DecodeToken

func (tm *TokenManager) DecodeToken(tokenString string) (map[string]any, error)

DecodeToken decodes a JWT token and returns its claims

func (*TokenManager) GenerateAccessToken

func (tm *TokenManager) GenerateAccessToken(jti string, payload map[string]any, configs ...*TokenConfig) (string, error)

GenerateAccessToken generates an access token with optional custom expiry

func (*TokenManager) GenerateRefreshToken

func (tm *TokenManager) GenerateRefreshToken(jti string, payload map[string]any, configs ...*TokenConfig) (string, error)

GenerateRefreshToken generates a refresh token with optional custom expiry

func (*TokenManager) GenerateRegisterToken

func (tm *TokenManager) GenerateRegisterToken(jti string, payload map[string]any, subject string, configs ...*TokenConfig) (string, error)

GenerateRegisterToken generates a register token with optional custom expiry

func (*TokenManager) GetPayload

func (tm *TokenManager) GetPayload(tokenString string) (map[string]any, error)

GetPayload extracts the payload from token claims

func (*TokenManager) GetSecret

func (tm *TokenManager) GetSecret() string

GetSecret returns the JWT secret

func (*TokenManager) GetTokenExpiry

func (tm *TokenManager) GetTokenExpiry(tokenString string) (time.Time, error)

GetTokenExpiry returns the expiry time of a token

func (*TokenManager) IsTokenExpired

func (tm *TokenManager) IsTokenExpired(tokenString string) bool

IsTokenExpired checks if a token is expired

func (*TokenManager) RefreshTokenIfNeeded

func (tm *TokenManager) RefreshTokenIfNeeded(tokenString string, refreshThreshold time.Duration) (string, bool, error)

RefreshTokenIfNeeded refreshes token if it's close to expiry

func (*TokenManager) SetAccessTokenExpiry

func (tm *TokenManager) SetAccessTokenExpiry(expiry time.Duration)

SetAccessTokenExpiry sets the default access token expiry

func (*TokenManager) SetRefreshTokenExpiry

func (tm *TokenManager) SetRefreshTokenExpiry(expiry time.Duration)

SetRefreshTokenExpiry sets the default refresh token expiry

func (*TokenManager) SetRegisterTokenExpiry

func (tm *TokenManager) SetRegisterTokenExpiry(expiry time.Duration)

SetRegisterTokenExpiry sets the default register token expiry

func (*TokenManager) SetSecret

func (tm *TokenManager) SetSecret(secret string)

SetSecret sets the JWT secret

func (*TokenManager) ValidateToken

func (tm *TokenManager) ValidateToken(tokenString string) (*jwtstd.Token, error)

ValidateToken validates a JWT token and returns the parsed token

type TokenValidator added in v0.2.0

type TokenValidator interface {
	ValidateToken(tokenString string) (any, error)
	DecodeToken(tokenString string) (map[string]any, error)
	IsTokenExpired(tokenString string) bool
}

TokenValidator is an interface for validating JWT tokens. This allows for easier testing and dependency injection.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL