Documentation
¶
Overview ¶
Package auth provides authentication utilities for CLI applications.
This package includes:
- JWT token generation and validation with customizable claims
- API key generation with configurable prefixes
- Token hashing utilities
JWT Usage ¶
Configure and use JWT tokens:
cfg := auth.JWTConfig{
Secret: []byte("your-32-byte-or-longer-secret-key"),
Issuer: "my-app",
AccessTokenTTL: 15 * time.Minute,
}
// Generate with default claims
token, err := auth.GenerateAccessToken(cfg, "user-123")
// Validate
claims, err := auth.ValidateAccessToken(cfg, token)
Custom Claims ¶
Extend BaseClaims for application-specific claims:
type MyClaims struct {
auth.BaseClaims
TenantID string `json:"tid"`
Role string `json:"role"`
}
// Generate with custom claims
token, err := auth.GenerateAccessTokenWithClaims(cfg, func(base auth.BaseClaims) MyClaims {
return MyClaims{
BaseClaims: base,
TenantID: "tenant-123",
Role: "admin",
}
})
// Validate with custom claims
claims, err := auth.ValidateAccessTokenAs[MyClaims](cfg, token)
API Keys ¶
Generate API keys with configurable prefixes:
cfg := auth.APIKeyConfig{
Prefix: "myapp_live_",
RandomLength: 32,
}
key, err := auth.GenerateAPIKey(cfg)
// key.Secret: "myapp_live_aBc123..."
// key.Hash: SHA-256 hash for storage
// key.Prefix: "myapp_live_aBc1..." (display prefix)
Token Hashing ¶
Hash tokens for secure storage:
hash := auth.HashToken(secretToken) // Store hash in database, verify by hashing incoming token
Index ¶
- Constants
- Variables
- func ExtractAPIKeyPrefix(key string, cfg APIKeyConfig) string
- func GenerateAccessToken(cfg JWTConfig, subject string) (string, error)
- func GenerateAccessTokenWithClaims[T jwt.Claims](cfg JWTConfig, builder func(BaseClaims) T) (string, error)
- func GenerateRefreshToken() (token, hash string, err error)
- func HashToken(token string) string
- func ValidateAPIKeyFormat(key string, cfg APIKeyConfig) bool
- func ValidateAccessTokenAs(cfg JWTConfig, tokenString string, claims jwt.Claims) error
- type APIKeyConfig
- type APIKeyWithSecret
- type BaseClaims
- type JWTConfig
- type TokenPair
Constants ¶
const ( DefaultAPIKeyPrefix = "key_" DefaultAPIKeyLength = 32 DefaultAPIKeyPrefixLength = 12 )
Default API key configuration.
const ( DefaultAccessTokenTTL = 15 * time.Minute DefaultRefreshTokenTTL = 7 * 24 * time.Hour )
Default token lifetimes.
Variables ¶
var ( // ErrInvalidToken indicates the token is malformed or has an invalid signature. ErrInvalidToken = errors.New("invalid token") // ErrTokenExpired indicates the token has expired. ErrTokenExpired = errors.New("token expired") // ErrSecretTooShort indicates the JWT secret is too short. ErrSecretTooShort = errors.New("JWT secret must be at least 32 bytes") // ErrInvalidAPIKey indicates the API key format is invalid. ErrInvalidAPIKey = errors.New("invalid API key format") )
Authentication errors.
Functions ¶
func ExtractAPIKeyPrefix ¶
func ExtractAPIKeyPrefix(key string, cfg APIKeyConfig) string
ExtractAPIKeyPrefix gets the display prefix from a full key.
func GenerateAccessToken ¶
GenerateAccessToken creates a new JWT access token with the given subject.
func GenerateAccessTokenWithClaims ¶
func GenerateAccessTokenWithClaims[T jwt.Claims](cfg JWTConfig, builder func(BaseClaims) T) (string, error)
GenerateAccessTokenWithClaims creates a JWT with custom claims. The builder function receives a BaseClaims with standard fields pre-populated.
func GenerateRefreshToken ¶
GenerateRefreshToken creates a new opaque refresh token. Returns the token (to give to client) and its hash (for storage).
func HashToken ¶
HashToken creates a SHA-256 hash of a token for secure storage. Use this to store refresh tokens or API keys in the database.
func ValidateAPIKeyFormat ¶
func ValidateAPIKeyFormat(key string, cfg APIKeyConfig) bool
ValidateAPIKeyFormat checks if a string matches the expected API key format.
func ValidateAccessTokenAs ¶
ValidateAccessTokenAs parses and validates a JWT into the provided claims pointer. Pass a pointer to your custom claims type.
Example:
claims := &MyClaims{}
if err := auth.ValidateAccessTokenAs(cfg, token, claims); err != nil {
return err
}
fmt.Println(claims.TenantID)
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
// Prefix is prepended to all keys (e.g., "myapp_live_").
// Defaults to "key_" if empty.
Prefix string
// RandomLength is the length of the random part.
// Defaults to 32 if zero.
RandomLength int
// PrefixLength is how many characters to show in the display prefix.
// Defaults to 12 if zero.
PrefixLength int
}
APIKeyConfig holds configuration for API key generation.
type APIKeyWithSecret ¶
type APIKeyWithSecret struct {
// ID is a unique identifier for the key.
ID string
// Secret is the full API key (e.g., "myapp_live_xxxx...").
// Only available at creation time.
Secret string
// Prefix is the display prefix (e.g., "myapp_live_xxxx...").
Prefix string
// Hash is the SHA-256 hash of the full key for storage.
Hash string
}
APIKeyWithSecret contains the full API key (only available at creation).
func GenerateAPIKey ¶
func GenerateAPIKey(cfg APIKeyConfig) (*APIKeyWithSecret, error)
GenerateAPIKey creates a new API key with the given configuration.
type BaseClaims ¶
type BaseClaims struct {
jwt.RegisteredClaims
}
BaseClaims represents the standard JWT claims. Embed this in custom claims types for application-specific data.
func ValidateAccessToken ¶
func ValidateAccessToken(cfg JWTConfig, tokenString string) (*BaseClaims, error)
ValidateAccessToken parses and validates a JWT, returning BaseClaims.
type JWTConfig ¶
type JWTConfig struct {
// Secret is the HMAC signing key (must be at least 32 bytes).
Secret []byte
// Issuer is the token issuer (e.g., "my-app").
Issuer string
// AccessTokenTTL is the lifetime of access tokens.
// Defaults to DefaultAccessTokenTTL (15 minutes) if zero.
AccessTokenTTL time.Duration
// RefreshTokenTTL is the lifetime of refresh tokens.
// Defaults to DefaultRefreshTokenTTL (7 days) if zero.
RefreshTokenTTL time.Duration
}
JWTConfig holds configuration for JWT generation and validation.
type TokenPair ¶
type TokenPair struct {
AccessToken string
RefreshToken string
ExpiresIn int64 // seconds until access token expires
}
TokenPair contains an access token and refresh token.
func GenerateTokenPair ¶
GenerateTokenPair creates both access and refresh tokens.
func GenerateTokenPairWithClaims ¶
func GenerateTokenPairWithClaims[T jwt.Claims](cfg JWTConfig, builder func(BaseClaims) T) (*TokenPair, string, error)
GenerateTokenPairWithClaims creates both tokens with custom claims.