Documentation
¶
Overview ¶
Package jwt provides JSON Web Token (JWT) functionality for authentication.
This package implements JWT token structures, creation, and validation for the AINative Code CLI tool. It supports both access tokens and refresh tokens with RS256 signing algorithm.
Token Types:
- Access Token: Short-lived (24 hours) token for API authentication
- Refresh Token: Long-lived (7 days) token for obtaining new access tokens
Features:
- RS256 (RSA with SHA-256) signing algorithm
- Custom claims for user identity and roles
- Token validation with expiration checking
- Public key caching for performance
Example usage:
import (
"github.com/AINative-studio/ainative-code/internal/auth/jwt"
"time"
)
// Create access token
claims := &jwt.AccessTokenClaims{
UserID: "user-123",
Email: "user@example.com",
Roles: []string{"user"},
}
token, err := jwt.CreateAccessToken(claims, privateKey)
// Validate token
validatedClaims, err := jwt.ValidateAccessToken(token, publicKey)
Index ¶
- Constants
- func CreateAccessToken(userID, email string, roles []string, privateKey *rsa.PrivateKey) (string, error)
- func CreateRefreshToken(userID, sessionID string, privateKey *rsa.PrivateKey) (string, error)
- func FormatPublicKeyPEM(publicKey *rsa.PublicKey) (string, error)
- func GetTokenExpiration(tokenString string) (time.Time, error)
- func IsTokenExpired(tokenString string) (bool, error)
- type APIValidationRequest
- type APIValidationResponse
- type APIValidator
- func (av *APIValidator) GetValidator() *Validator
- func (av *APIValidator) InvalidateCache() error
- func (av *APIValidator) ValidateAccessToken(ctx context.Context, tokenString string) (*AccessTokenClaims, error)
- func (av *APIValidator) ValidateRefreshToken(ctx context.Context, tokenString string) (*RefreshTokenClaims, error)
- func (av *APIValidator) ValidateToken(ctx context.Context, tokenString string) (*ValidationResult, error)
- type AccessTokenClaims
- type KeyFetcher
- type PublicKeyCache
- type PublicKeyCacheInfo
- type RefreshTokenClaims
- type TokenPair
- type ValidationResult
- type Validator
- func (v *Validator) GetCacheInfo() *PublicKeyCacheInfo
- func (v *Validator) InvalidateCache() error
- func (v *Validator) SetInvalidateFunc(fn func() error)
- func (v *Validator) ValidateAccessToken(tokenString string) (*AccessTokenClaims, error)
- func (v *Validator) ValidateRefreshToken(tokenString string) (*RefreshTokenClaims, error)
- func (v *Validator) ValidateToken(tokenString string) (*ValidationResult, error)
Constants ¶
const ( // DefaultAPITimeout is the default timeout for API validation requests DefaultAPITimeout = 10 * time.Second // ValidationEndpoint is the API endpoint for token validation ValidationEndpoint = "/api/auth/validate" )
const ( // Issuer is the token issuer Issuer = "ainative-auth" // Audience is the intended token audience Audience = "ainative-code" // AccessTokenDuration is the lifetime of an access token AccessTokenDuration = 24 * time.Hour // RefreshTokenDuration is the lifetime of a refresh token RefreshTokenDuration = 7 * 24 * time.Hour // SigningMethod is the algorithm used for signing tokens SigningMethod = "RS256" )
const ( // PublicKeyCacheTTL is the time-to-live for cached public keys PublicKeyCacheTTL = 5 * time.Minute // PublicKeyRefreshThreshold is when to refresh the key before expiry PublicKeyRefreshThreshold = 1 * time.Minute )
Variables ¶
This section is empty.
Functions ¶
func CreateAccessToken ¶
func CreateAccessToken(userID, email string, roles []string, privateKey *rsa.PrivateKey) (string, error)
CreateAccessToken creates a new access token with the given claims.
func CreateRefreshToken ¶
func CreateRefreshToken(userID, sessionID string, privateKey *rsa.PrivateKey) (string, error)
CreateRefreshToken creates a new refresh token with the given claims.
func FormatPublicKeyPEM ¶
FormatPublicKeyPEM formats an RSA public key as PEM.
func GetTokenExpiration ¶
GetTokenExpiration returns the expiration time of a token without validation.
func IsTokenExpired ¶
IsTokenExpired checks if a token has expired without full validation.
Types ¶
type APIValidationRequest ¶
type APIValidationRequest struct {
Token string `json:"token"`
}
APIValidationRequest represents the request payload for token validation.
type APIValidationResponse ¶
type APIValidationResponse struct {
Valid bool `json:"valid"`
Message string `json:"message,omitempty"`
Expired bool `json:"expired"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
PublicKey string `json:"public_key,omitempty"`
}
APIValidationResponse represents the response from the validation API.
type APIValidator ¶
type APIValidator struct {
// contains filtered or unexported fields
}
APIValidator validates tokens using the AINative API.
func NewAPIValidator ¶
func NewAPIValidator(baseURL string, httpClient *http.Client) *APIValidator
NewAPIValidator creates a new API validator with a local validator fallback.
func (*APIValidator) GetValidator ¶
func (av *APIValidator) GetValidator() *Validator
GetValidator returns the underlying local validator.
func (*APIValidator) InvalidateCache ¶
func (av *APIValidator) InvalidateCache() error
InvalidateCache invalidates both API and local caches.
func (*APIValidator) ValidateAccessToken ¶
func (av *APIValidator) ValidateAccessToken(ctx context.Context, tokenString string) (*AccessTokenClaims, error)
ValidateAccessToken validates an access token using API and local validation.
func (*APIValidator) ValidateRefreshToken ¶
func (av *APIValidator) ValidateRefreshToken(ctx context.Context, tokenString string) (*RefreshTokenClaims, error)
ValidateRefreshToken validates a refresh token using API and local validation.
func (*APIValidator) ValidateToken ¶
func (av *APIValidator) ValidateToken(ctx context.Context, tokenString string) (*ValidationResult, error)
ValidateToken validates a token using API and returns validation result.
type AccessTokenClaims ¶
type AccessTokenClaims struct {
// Standard JWT claims
jwt.RegisteredClaims
// UserID is the unique identifier for the user
UserID string `json:"user_id"`
// Email is the user's email address
Email string `json:"email"`
// Roles are the user's authorization roles
Roles []string `json:"roles"`
}
AccessTokenClaims represents the claims in an access token.
func ValidateAccessToken ¶
func ValidateAccessToken(tokenString string, publicKey *rsa.PublicKey) (*AccessTokenClaims, error)
ValidateAccessToken validates an access token and returns the claims.
type KeyFetcher ¶
KeyFetcher is a function that fetches the public key from a remote source.
type PublicKeyCache ¶
type PublicKeyCache struct {
// Key is the public key in PEM format
Key string
// CachedAt is when the key was cached
CachedAt time.Time
// ExpiresAt is when the cached key expires
ExpiresAt time.Time
}
PublicKeyCache represents a cache for public keys.
type PublicKeyCacheInfo ¶
type PublicKeyCacheInfo struct {
HasKey bool
CachedAt time.Time
ExpiresAt time.Time
TTL time.Duration
IsValid bool
}
PublicKeyCacheInfo represents information about the cached public key.
type RefreshTokenClaims ¶
type RefreshTokenClaims struct {
// Standard JWT claims
jwt.RegisteredClaims
// UserID is the unique identifier for the user
UserID string `json:"user_id"`
// SessionID is the unique identifier for the session
SessionID string `json:"session_id"`
}
RefreshTokenClaims represents the claims in a refresh token.
func ValidateRefreshToken ¶
func ValidateRefreshToken(tokenString string, publicKey *rsa.PublicKey) (*RefreshTokenClaims, error)
ValidateRefreshToken validates a refresh token and returns the claims.
type TokenPair ¶
type TokenPair struct {
// AccessToken is the JWT access token
AccessToken string `json:"access_token"`
// RefreshToken is the JWT refresh token
RefreshToken string `json:"refresh_token"`
// ExpiresIn is the access token expiration time in seconds
ExpiresIn int64 `json:"expires_in"`
// TokenType is the type of token (always "Bearer")
TokenType string `json:"token_type"`
}
TokenPair represents a pair of access and refresh tokens.
func CreateTokenPair ¶
func CreateTokenPair(userID, email string, roles []string, sessionID string, privateKey *rsa.PrivateKey) (*TokenPair, error)
CreateTokenPair creates both access and refresh tokens.
type ValidationResult ¶
type ValidationResult struct {
// Valid indicates whether the token is valid
Valid bool
// Claims contains the validated token claims
Claims interface{}
// Error contains any validation error
Error error
// Expired indicates whether the token has expired
Expired bool
// ExpiresAt is when the token expires
ExpiresAt time.Time
}
ValidationResult represents the result of token validation.
func ValidateToken ¶
func ValidateToken(tokenString string, publicKey *rsa.PublicKey) (*ValidationResult, error)
ValidateToken performs basic validation on a token string and returns metadata.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator handles JWT validation with public key caching.
func NewValidator ¶
func NewValidator(keyFetcher KeyFetcher) *Validator
NewValidator creates a new JWT validator with public key caching.
func (*Validator) GetCacheInfo ¶
func (v *Validator) GetCacheInfo() *PublicKeyCacheInfo
GetCacheInfo returns information about the cached key.
func (*Validator) InvalidateCache ¶
InvalidateCache invalidates the cached public key.
func (*Validator) SetInvalidateFunc ¶
SetInvalidateFunc sets a custom cache invalidation function.
func (*Validator) ValidateAccessToken ¶
func (v *Validator) ValidateAccessToken(tokenString string) (*AccessTokenClaims, error)
ValidateAccessToken validates an access token using cached public key.
func (*Validator) ValidateRefreshToken ¶
func (v *Validator) ValidateRefreshToken(tokenString string) (*RefreshTokenClaims, error)
ValidateRefreshToken validates a refresh token using cached public key.
func (*Validator) ValidateToken ¶
func (v *Validator) ValidateToken(tokenString string) (*ValidationResult, error)
ValidateToken validates a token and returns validation result.