auth

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 5 Imported by: 2

README

auth

Authentication building blocks with JWT, password hashing, OIDC verification, and shared token validation interfaces.

For authorization (permission checking, RBAC), see authz.

Install

go get github.com/kbukum/gokit/auth@latest

Quick Start

Token Validation Interface

The auth.TokenValidator interface is the shared contract used by middleware and interceptors:

import "github.com/kbukum/gokit/auth"

// From a JWT service
validator := auth.NewValidator(jwtSvc.ValidatorFunc())

// From a custom function
validator := auth.TokenValidatorFunc(func(token string) (any, error) {
    return myCustomValidation(token)
})
Provider Registry

Register multiple validators and select by name:

reg := auth.NewRegistry()
reg.Register("jwt", auth.NewValidator(jwtSvc.ValidatorFunc()))
reg.Register("apikey", auth.TokenValidatorFunc(myAPIKeyValidator))
reg.SetDefault("jwt")

// In middleware setup
validator, _ := reg.Default()
router.Use(middleware.Auth(validator))
JWT Token Service
import "github.com/kbukum/gokit/auth/jwt"

cfg := &jwt.Config{Secret: "my-secret", Method: "HS256", AccessTokenTTL: 15 * time.Minute}
cfg.ApplyDefaults()

svc, _ := jwt.NewService[*MyClaims](cfg, func() *MyClaims { return &MyClaims{} })
token, _ := svc.GenerateAccess(claims)
parsed, _ := svc.Parse(token)
Password Hashing
import "github.com/kbukum/gokit/auth/password"

hasher := password.NewHasher(password.Config{Algorithm: "bcrypt"})
hash, _ := hasher.Hash("my-password")
err := hasher.Verify("my-password", hash)
OIDC Verification
import "github.com/kbukum/gokit/auth/oidc"

verifier, _ := oidc.NewVerifier(ctx, "https://issuer.example.com", oidc.VerifierConfig{ClientID: "my-app"})
idToken, _ := verifier.Verify(ctx, rawIDToken)
Composable Config

Only configure what you need — unused sections are nil:

auth:
  enabled: true
  jwt:
    secret: "my-secret"
    access_token_ttl: "15m"
  # password and oidc are omitted — no validation or defaults applied

Key Types & Functions

auth (top-level)
Symbol Description
TokenValidator Interface — ValidateToken(token) (any, error)
TokenValidatorFunc Adapter for ordinary functions
TokenGenerator Interface — GenerateToken(claims) (string, error)
NewValidator(fn) Bridge helper for ValidatorFunc()
Registry Thread-safe named validator registry
NewRegistry() Constructor for Registry
Config Composable config with pointer sub-configs
auth/jwt
Symbol Description
Service[T] Generic JWT service parameterized by claims type
NewService[T](cfg, newEmpty) Constructor with claims factory
Generate(claims) Sign a token
GenerateAccess(claims) Access token with configured TTL
GenerateRefresh(claims) Refresh token with configured TTL
Parse(tokenString) Parse and validate a token
ValidatorFunc() Returns func(string) (any, error) for middleware
Config Secret, PrivateKeyPath, Method, Issuer, Audience, TTLs
auth/password
Symbol Description
Hasher Interface — Hash(password), Verify(password, hash)
NewHasher(cfg) Factory from config (bcrypt or argon2id)
GenerateToken(length) Cryptographically secure random token
HashSHA256(input) SHA256 hex digest for token storage
auth/authctx
Symbol Description
Set(ctx, claims) Store claims in context
Get[T](ctx) Type-safe claims retrieval
MustGet[T](ctx) Panic if claims missing
GetOrError[T](ctx) Error-based retrieval
auth/oidc
Symbol Description
Provider Interface — AuthURL, Exchange, UserInfo
Verifier OIDC token verification with JWKS caching
NewVerifier(ctx, issuer, cfg) Create verifier with auto-discovery
NewPKCE() Generate PKCE code verifier/challenge pair
GenerateState() CSRF state token

← Back to main gokit README

Documentation

Overview

Package auth provides authentication building blocks.

This is a Go module (github.com/kbukum/gokit/auth) with focused subpackages:

  • auth/jwt — Generic JWT token service using Go generics
  • auth/password — Password hashing (bcrypt, argon2id) and secure token generation
  • auth/authctx — Type-safe request context propagation for claims
  • auth/oidc — OIDC/OAuth2 building blocks (discovery, verification, PKCE)

The top-level package provides shared contracts:

  • TokenValidator — interface for validating tokens (JWT, OIDC, API key, etc.)
  • TokenGenerator — interface for generating signed tokens
  • Registry — thread-safe registry of named TokenValidator instances
  • Config — composable configuration with pointer sub-configs

For authorization (permission checking, RBAC), see github.com/kbukum/gokit/authz.

All packages follow gokit conventions: Config structs with ApplyDefaults()/Validate(), constructor functions, and mapstructure tags for config file loading.

The top-level Config composes subpackage configs as pointers — only configure what you need:

auth:
  enabled: true
  jwt:
    secret: "my-secret"
    access_token_ttl: "15m"
  password:
    algorithm: "bcrypt"
    bcrypt_cost: 12

Register validators for use with middleware:

reg := auth.NewRegistry()
reg.Register("jwt", jwtSvc.AsValidator())
validator, _ := reg.Default()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Enabled controls whether authentication is active.
	Enabled bool `mapstructure:"enabled"`

	// JWT configures the JWT token service (nil if not used).
	JWT *jwt.Config `mapstructure:"jwt"`

	// Password configures password hashing (nil if not used).
	Password *password.Config `mapstructure:"password"`

	// OIDC configures OIDC provider verification (nil if not used).
	OIDC *oidc.Config `mapstructure:"oidc"`
}

Config holds all authentication configuration. It composes subpackage configs for loading from YAML/env via mapstructure. Sub-configs are pointers so unused features are nil and don't force unnecessary validation or defaults.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults sets sensible defaults for non-nil sub-configurations.

func (*Config) Describe

func (c *Config) Describe() string

Describe returns a human-readable one-liner for the startup summary. Example: "JWT(HS256) TTL=15m0s password=bcrypt OIDC(issuer.com)"

func (*Config) Validate

func (c *Config) Validate() error

Validate checks all non-nil sub-configurations.

type Registry

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

Registry is a thread-safe registry of named TokenValidator instances. Projects register their validators (JWT, OIDC, API key, etc.) by name and retrieve them in middleware or interceptors.

Usage:

reg := auth.NewRegistry()
reg.Register("jwt", jwtSvc.AsValidator())
reg.Register("apikey", auth.TokenValidatorFunc(myAPIKeyValidator))
reg.SetDefault("jwt")

// In middleware setup
validator, _ := reg.Default()

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new empty Registry.

func (*Registry) Default

func (r *Registry) Default() (TokenValidator, bool)

Default returns the default TokenValidator. The default is the first registered validator unless overridden with SetDefault.

func (*Registry) Get

func (r *Registry) Get(name string) (TokenValidator, bool)

Get returns the TokenValidator registered under the given name. Returns nil and false if not found.

func (*Registry) MustGet

func (r *Registry) MustGet(name string) TokenValidator

MustGet returns the TokenValidator registered under the given name. Panics if the name is not registered.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns all registered validator names.

func (*Registry) Register

func (r *Registry) Register(name string, v TokenValidator)

Register adds a named TokenValidator to the registry. If this is the first validator registered, it becomes the default.

func (*Registry) SetDefault

func (r *Registry) SetDefault(name string) error

SetDefault sets the default validator by name. The name must already be registered.

type TokenGenerator

type TokenGenerator interface {
	GenerateToken(claims any) (string, error)
}

TokenGenerator generates a signed token from claims. This is the token creation contract — services use this to issue tokens without depending on specific signing implementations.

type TokenGeneratorFunc

type TokenGeneratorFunc func(claims any) (string, error)

TokenGeneratorFunc adapts an ordinary function to the TokenGenerator interface.

func (TokenGeneratorFunc) GenerateToken

func (f TokenGeneratorFunc) GenerateToken(claims any) (string, error)

GenerateToken implements TokenGenerator.

type TokenValidator

type TokenValidator interface {
	ValidateToken(token string) (any, error)
}

TokenValidator validates a token string and returns the parsed claims. This is the core authentication contract — middleware and interceptors depend on this interface rather than specific implementations (JWT, OIDC, etc.).

The returned value can be any type (typically a project-specific claims struct). It is stored in request context via authctx.Set and retrieved with authctx.Get[T].

Implementations:

  • jwt.Service[T].AsValidator() — validates JWT tokens
  • oidc.Verifier can be adapted via TokenValidatorFunc
  • Projects can implement custom validators (API keys, opaque tokens, etc.)

func NewValidator

func NewValidator(fn func(string) (any, error)) TokenValidator

NewValidator creates a TokenValidator from a validation function. This is a convenience wrapper for TokenValidatorFunc, useful for bridging typed services like jwt.Service[T]:

validator := auth.NewValidator(jwtSvc.ValidatorFunc())

type TokenValidatorFunc

type TokenValidatorFunc func(token string) (any, error)

TokenValidatorFunc adapts an ordinary function to the TokenValidator interface. This is the simplest way to create a validator:

validator := auth.TokenValidatorFunc(func(token string) (any, error) {
    return myCustomValidation(token)
})

func (TokenValidatorFunc) ValidateToken

func (f TokenValidatorFunc) ValidateToken(token string) (any, error)

ValidateToken implements TokenValidator.

Directories

Path Synopsis
Package authctx provides type-safe context propagation for authentication claims.
Package authctx provides type-safe context propagation for authentication claims.
Package jwt provides a generic JWT token service using Go generics.
Package jwt provides a generic JWT token service using Go generics.
Package oidc provides OpenID Connect building blocks for authentication.
Package oidc provides OpenID Connect building blocks for authentication.
Package password provides password hashing and verification utilities.
Package password provides password hashing and verification utilities.

Jump to

Keyboard shortcuts

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