jwtutil

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 10 Imported by: 1

README

jwtutil

Reusable JWT authentication layer built on common/crypto, adding token pairs, refresh flows, revocation, and HTTP helpers.

Features

  • Token pairs: short-lived access token + long-lived refresh token
  • Refresh flow: issue new access token from a valid refresh token
  • Revocation / blacklist via pluggable TokenStore
  • Claims builder with roles and permissions
  • HTTP helpers: bearer token extraction, context-based claim retrieval

Key types

  • Auth -- the main JWT auth manager
  • Config -- manager configuration (secret/keys, TTLs, store, leeway)
  • Claims -- decoded JWT claims with auth-specific fields (roles, permissions)
  • TokenPair -- access + refresh token response
  • TokenStore -- revocation interface (Revoke, IsRevoked, MarkUsed)
  • MemoryTokenStore -- in-process token store implementation
  • TokenType -- TokenTypeAccess, TokenTypeRefresh

Key functions

  • New(cfg) -- create an Auth manager
  • Auth.Login(subject, opts...) -- issue a token pair
  • Auth.Verify(token) -- verify and return claims
  • Auth.Refresh(refreshToken) -- issue new pair from refresh token
  • Auth.Revoke(ctx, token) -- revoke a token
  • ExtractBearerToken(header) -- extract token from Authorization header
  • NewMemoryTokenStore() -- in-memory revocation store

Quick start

import "github.com/LingByte/ling-base/common/jwtutil"

auth, err := jwtutil.New(jwtutil.Config{
    Secret:     []byte("my-32-byte-secret-1234567890123456"),
    Issuer:     "my-app",
    AccessTTL:  15 * time.Minute,
    RefreshTTL: 7 * 24 * time.Hour,
})
if err != nil {
    log.Fatal(err)
}

pair, err := auth.Login("user-123", jwtutil.Roles("admin"))
claims, err := auth.Verify(pair.AccessToken)

License

MIT

Documentation

Overview

Package jwtutil provides a reusable, library-friendly JWT authentication layer built on top of the `common/crypto` JWT primitives.

It adds the pieces needed for real-world auth flows that the low-level crypto.JWT type does not cover:

  • Token pairs: short-lived access token + long-lived refresh token.
  • Refresh flow: issue a new access token from a valid refresh token.
  • Revocation / blacklist: pluggable TokenStore for invalidating tokens before their natural expiry (logout, password change, etc.).
  • Claims builder: fluent API for constructing common claim sets.
  • HTTP helpers: extract bearer tokens, context-based claim retrieval, and a generic auth middleware wrapper.

Quick start

auth, err := jwtutil.New(jwtutil.Config{
    Secret:      []byte("my-32-byte-secret-1234567890123456"),
    Issuer:      "my-app",
    AccessTTL:   15 * time.Minute,
    RefreshTTL:  7 * 24 * time.Hour,
})
if err != nil {
    log.Fatal(err)
}

// Issue a token pair at login.
pair, err := auth.Login("user-123", jwtutil.Roles("admin"))
// pair.AccessToken, pair.RefreshToken

// Verify an access token (from Authorization: Bearer <token>).
claims, err := auth.Verify(pair.AccessToken)

// Refresh.
pair, err = auth.Refresh(pair.RefreshToken)

// Revoke (logout).
auth.Revoke(context.Background(), pair.AccessToken)

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidToken is returned when a token is malformed or has an invalid signature.
	ErrInvalidToken = errors.New("jwtutil: invalid token")
	// ErrTokenExpired is returned when a token has passed its expiry time.
	ErrTokenExpired = errors.New("jwtutil: token expired")
	// ErrTokenNotYetValid is returned when a token's nbf claim is in the future.
	ErrTokenNotYetValid = errors.New("jwtutil: token not yet valid")
	// ErrTokenRevoked is returned when a token has been revoked via the TokenStore.
	ErrTokenRevoked = errors.New("jwtutil: token revoked")
	// ErrWrongTokenType is returned when a refresh token is used where an access
	// token is expected, or vice versa.
	ErrWrongTokenType = errors.New("jwtutil: wrong token type")
)

Functions

func ContextWithClaims

func ContextWithClaims(ctx context.Context, claims *Claims) context.Context

ContextWithClaims stores claims in a context.

func ExtractBearer

func ExtractBearer(authHeader string) (string, error)

ExtractBearer extracts the token from an "Authorization: Bearer <token>" header value. Returns the token and nil if successful.

Types

type Auth

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

Auth is the JWT authentication manager. It signs, verifies, refreshes, and revokes tokens.

func New

func New(cfg Config) (*Auth, error)

New creates a new Auth manager from the given Config.

func (*Auth) IssueAccess

func (a *Auth) IssueAccess(subject string, opts ...IssueOption) (string, error)

IssueAccess issues a standalone access token (without a refresh token).

func (*Auth) Login

func (a *Auth) Login(subject string, opts ...IssueOption) (*TokenPair, error)

Login issues a token pair (access + refresh) for the given subject. Additional claims can be set via options.

func (*Auth) Refresh

func (a *Auth) Refresh(refreshToken string) (*TokenPair, error)

Refresh validates a refresh token and issues a new token pair. If the TokenStore supports MarkUsed, the old refresh token is marked as used to prevent replay attacks.

func (*Auth) Revoke

func (a *Auth) Revoke(ctx context.Context, accessToken string) error

Revoke marks an access token as revoked. Requires a TokenStore.

func (*Auth) RevokeRefresh

func (a *Auth) RevokeRefresh(ctx context.Context, refreshToken string) error

RevokeRefresh marks a refresh token as revoked. Requires a TokenStore.

func (*Auth) SetIDGenerator

func (a *Auth) SetIDGenerator(g IDGenerator)

SetIDGenerator overrides the default jti generator.

func (*Auth) SetStore

func (a *Auth) SetStore(s TokenStore)

SetStore overrides the token store (can also be set via Config.Store).

func (*Auth) Verify

func (a *Auth) Verify(token string) (*Claims, error)

Verify validates an access token and returns the claims. It checks signature, expiry, nbf, token type, and revocation status.

func (*Auth) VerifyRefresh

func (a *Auth) VerifyRefresh(token string) (*Claims, error)

VerifyRefresh validates a refresh token and returns the claims.

type Claims

type Claims struct {
	// Standard JWT claims.
	Issuer    string `json:"iss,omitempty"`
	Subject   string `json:"sub,omitempty"`
	Audience  string `json:"aud,omitempty"`
	ExpiresAt int64  `json:"exp,omitempty"`
	NotBefore int64  `json:"nbf,omitempty"`
	IssuedAt  int64  `json:"iat,omitempty"`
	ID        string `json:"jti,omitempty"`

	// Auth-specific claims.
	TokenType   TokenType `json:"type,omitempty"`
	Roles       []string  `json:"roles,omitempty"`
	Permissions []string  `json:"perms,omitempty"`

	// Extra holds any additional non-standard claims.
	Extra map[string]any `json:"-"`
}

Claims represents the decoded JWT claims with auth-specific fields.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) *Claims

ClaimsFromContext retrieves claims from a context, or nil if not present.

func (*Claims) HasPermission

func (c *Claims) HasPermission(perm string) bool

HasPermission returns true if the claims include the given permission.

func (*Claims) HasRole

func (c *Claims) HasRole(role string) bool

HasRole returns true if the claims include the given role.

func (*Claims) IsAccess

func (c *Claims) IsAccess() bool

IsAccess returns true if this is an access token.

func (*Claims) IsRefresh

func (c *Claims) IsRefresh() bool

IsRefresh returns true if this is a refresh token.

type Config

type Config struct {
	// Secret is the HMAC secret key (for HS256/HS512). Required if using HMAC.
	Secret []byte
	// Algorithm is the signing algorithm. Default: HS256.
	Algorithm crypto.JWTAlgorithm
	// RSAPriv is the RSA private key for RS256 signing. Required if using RS256.
	RSAPriv *rsa.PrivateKey
	// RSAPub is the RSA public key for RS256 verification. Required if using RS256.
	RSAPub *rsa.PublicKey
	// Issuer is the iss claim. Optional.
	Issuer string
	// Audience is the aud claim. Optional.
	Audience string
	// AccessTTL is the access token lifetime. Default: 15m.
	AccessTTL time.Duration
	// RefreshTTL is the refresh token lifetime. Default: 168h (7 days).
	RefreshTTL time.Duration
	// Store is the optional token revocation store. If nil, revocation is
	// not enforced (tokens remain valid until expiry).
	Store TokenStore
	// Leeway is the clock skew tolerance for exp/nbf checks. Default: 0.
	Leeway time.Duration
}

Config configures the JWT auth manager.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

type CounterIDGenerator

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

CounterIDGenerator is a deterministic, monotonic ID generator for testing.

func NewCounterIDGenerator

func NewCounterIDGenerator() *CounterIDGenerator

NewCounterIDGenerator creates a counter-based ID generator starting at 1.

func (*CounterIDGenerator) NewID

func (g *CounterIDGenerator) NewID() (string, error)

type IDGenerator

type IDGenerator interface {
	NewID() (string, error)
}

IDGenerator generates unique token IDs (jti claim).

type IssueOption

type IssueOption func(*Claims)

IssueOption modifies the claims during token issuance.

func WithAudience

func WithAudience(aud string) IssueOption

WithAudience overrides the audience claim for this token.

func WithExtra

func WithExtra(key string, value any) IssueOption

WithExtra sets an extra claim key-value pair.

func WithPermissions

func WithPermissions(perms ...string) IssueOption

WithPermissions sets the permissions claim.

func WithRoles

func WithRoles(roles ...string) IssueOption

WithRoles sets the roles claim.

type MemoryTokenStore

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

MemoryTokenStore is an in-process TokenStore. Useful for single-instance deployments and testing. Not suitable for multi-instance setups.

func NewMemoryTokenStore

func NewMemoryTokenStore() *MemoryTokenStore

NewMemoryTokenStore creates an in-memory token store.

func (*MemoryTokenStore) Cleanup

func (s *MemoryTokenStore) Cleanup()

Cleanup removes expired entries from the store. This should be called periodically to prevent unbounded memory growth.

func (*MemoryTokenStore) IsRevoked

func (s *MemoryTokenStore) IsRevoked(_ context.Context, jti string) (bool, error)

IsRevoked returns true if the token ID has been revoked and its revocation expiry has not passed.

func (*MemoryTokenStore) Len

func (s *MemoryTokenStore) Len() (revoked, used int)

Len returns the number of revoked and used entries.

func (*MemoryTokenStore) MarkUsed

func (s *MemoryTokenStore) MarkUsed(_ context.Context, jti string, expiry time.Time) (bool, error)

MarkUsed marks a refresh token ID as used. Returns true if it was not previously used, false if already used.

func (*MemoryTokenStore) Revoke

func (s *MemoryTokenStore) Revoke(_ context.Context, jti string, expiry time.Time) error

Revoke marks the token ID as revoked until the given expiry.

type TokenPair

type TokenPair struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"` // access token TTL in seconds
	TokenType    string `json:"token_type"` // always "Bearer"
}

TokenPair holds an access token and its associated refresh token.

type TokenStore

type TokenStore interface {
	// Revoke marks the token ID (jti) as revoked until the given expiry.
	Revoke(ctx context.Context, jti string, expiry time.Time) error

	// IsRevoked returns true if the token ID has been revoked.
	IsRevoked(ctx context.Context, jti string) (bool, error)

	// MarkUsed marks a refresh token ID as used (for one-time refresh tokens).
	// Returns true if it was not previously used, false if already used.
	MarkUsed(ctx context.Context, jti string, expiry time.Time) (bool, error)
}

TokenStore is a pluggable store for tracking revoked tokens. Implementations can be in-memory (for single-instance), Redis, etc.

A token is considered revoked if IsRevoked returns true for its jti. The store is also used to track refresh tokens that have been used (to prevent replay attacks).

type TokenType

type TokenType string

TokenType distinguishes access tokens from refresh tokens.

const (
	// TokenTypeAccess is the short-lived token used for API authentication.
	TokenTypeAccess TokenType = "access"
	// TokenTypeRefresh is the long-lived token used to obtain new access tokens.
	TokenTypeRefresh TokenType = "refresh"
)

Directories

Path Synopsis
gin module

Jump to

Keyboard shortcuts

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