jwt

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: Apache-2.0 Imports: 2 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

This section is empty.

Functions

func ContainsAnyValue added in v0.1.7

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

ContainsAnyValue checks if a slice contains any of the specified values

func ContainsValue added in v0.1.7

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

ContainsValue checks if a slice contains a specific value

func GetAudience added in v0.1.7

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

GetAudience extracts audience (aud) from token claims

func GetBool added in v0.1.7

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

GetBool safely extracts boolean value from any map

func GetExpiration added in v0.1.7

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

GetExpiration extracts expiration time from token claims

func GetFloat64 added in v0.1.7

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

GetFloat64 safely extracts float64 value from any map

func GetInt added in v0.1.7

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

GetInt safely extracts int value from any map

func GetInt64 added in v0.1.7

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

GetInt64 safely extracts int64 value from any map

func GetIssuedAt added in v0.1.7

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

GetIssuedAt extracts issued at time from token claims

func GetIssuer added in v0.1.7

func GetIssuer(claims map[string]any) string

GetIssuer extracts issuer (iss) from token claims

func GetMap added in v0.1.7

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

GetMap safely extracts nested map from any map

func GetNotBefore added in v0.1.7

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

GetNotBefore extracts not before time from token claims

func GetPayload added in v0.1.7

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

GetPayload extracts payload from token claims

func GetPayloadBool added in v0.1.7

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

GetPayloadBool extracts boolean value from payload

func GetPayloadInt added in v0.1.7

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

GetPayloadInt extracts int value from payload

func GetPayloadString added in v0.1.7

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

GetPayloadString extracts string value from payload

func GetPayloadStringSlice added in v0.1.7

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

GetPayloadStringSlice extracts string slice from payload

func GetString added in v0.1.7

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

GetString safely extracts string value from any map

func GetStringSlice added in v0.1.7

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

GetStringSlice safely extracts string slice from any map

func GetSubject added in v0.1.7

func GetSubject(claims map[string]any) string

GetSubject extracts subject (sub) from token claims

func GetTokenID added in v0.1.7

func GetTokenID(claims map[string]any) string

GetTokenID extracts JWT ID (jti) from token claims

func HasPayloadValue added in v0.1.7

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

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

func IsAccessToken added in v0.1.4

func IsAccessToken(claims map[string]any) bool

IsAccessToken checks if token is an access token

func IsRefreshToken added in v0.1.4

func IsRefreshToken(claims map[string]any) bool

IsRefreshToken checks if token is a refresh token

func IsTokenActive added in v0.1.7

func IsTokenActive(claims map[string]any) bool

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

func IsTokenExpired added in v0.1.7

func IsTokenExpired(claims map[string]any) bool

IsTokenExpired checks if token is expired based on claims

func IsTokenStale added in v0.1.4

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

IsTokenStale checks if token is older than specified duration

func ValidateTokenTiming added in v0.1.7

func ValidateTokenTiming(claims map[string]any) error

ValidateTokenTiming validates token timing (exp, iat, nbf)

func ValidateTokenType added in v0.1.4

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

ValidateTokenType ensures token is of expected type

Types

type TokenConfig added in v0.1.8

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 added in v0.1.2

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

TokenManager handles JWT token operations

func NewTokenManager added in v0.1.2

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

NewTokenManager creates a new TokenManager instance with optional configuration

func (*TokenManager) DecodeToken added in v0.1.2

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

DecodeToken decodes a JWT token and returns its claims

func (*TokenManager) GenerateAccessToken added in v0.1.2

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 added in v0.1.2

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 added in v0.1.2

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 added in v0.1.7

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

GetPayload extracts the payload from token claims

func (*TokenManager) GetSecret added in v0.1.10

func (tm *TokenManager) GetSecret() string

GetSecret returns the JWT secret

func (*TokenManager) GetTokenExpiry added in v0.1.4

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

GetTokenExpiry returns the expiry time of a token

func (*TokenManager) IsTokenExpired added in v0.1.2

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

IsTokenExpired checks if a token is expired

func (*TokenManager) RefreshTokenIfNeeded added in v0.1.4

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

RefreshTokenIfNeeded refreshes token if it's close to expiry

func (*TokenManager) SetAccessTokenExpiry added in v0.1.8

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

SetAccessTokenExpiry sets the default access token expiry

func (*TokenManager) SetRefreshTokenExpiry added in v0.1.8

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

SetRefreshTokenExpiry sets the default refresh token expiry

func (*TokenManager) SetRegisterTokenExpiry added in v0.1.8

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

SetRegisterTokenExpiry sets the default register token expiry

func (*TokenManager) SetSecret added in v0.1.10

func (tm *TokenManager) SetSecret(secret string)

SetSecret sets the JWT secret

func (*TokenManager) ValidateToken added in v0.1.2

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

ValidateToken validates a JWT token and returns the parsed token

Jump to

Keyboard shortcuts

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