jwt

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package jwt provides JWT token generation and validation for CoreForge applications.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoSigningKey is returned when no signing key is configured.
	ErrNoSigningKey = errors.New("no signing key configured: provide Secret or PrivateKey")
	// ErrInvalidAlgorithm is returned when an unsupported algorithm is specified.
	ErrInvalidAlgorithm = errors.New("invalid signing algorithm")
	// ErrMissingPublicKey is returned when PrivateKey is set but PublicKey is not.
	ErrMissingPublicKey = errors.New("public key required when using asymmetric signing")
)
View Source
var (
	// ErrInvalidToken is returned when a token cannot be parsed or validated.
	ErrInvalidToken = errors.New("invalid token")
	// ErrTokenExpired is returned when a token has expired.
	ErrTokenExpired = errors.New("token expired")
	// ErrWrongTokenType is returned when the token type doesn't match expectations.
	ErrWrongTokenType = errors.New("wrong token type")
)

Functions

func ComputeTokenHash

func ComputeTokenHash(token string) string

ComputeTokenHash computes the base64url-encoded SHA-256 hash of a token string. This is used for the ath (access token hash) claim in DPoP proofs.

Types

type CNFClaim

type CNFClaim struct {
	// JKT is the JWK thumbprint of the DPoP public key (RFC 7638).
	JKT string `json:"jkt,omitempty"`
}

CNFClaim represents the confirmation claim (cnf) for DPoP-bound tokens. Per RFC 9449, this contains the JWK thumbprint of the DPoP public key.

type Claims

type Claims struct {
	jwt.RegisteredClaims

	// UserID is the CoreForge user ID.
	UserID uuid.UUID `json:"uid,omitempty"`

	// Email is the user's email address.
	Email string `json:"email,omitempty"`

	// Name is the user's display name.
	Name string `json:"name,omitempty"`

	// OrganizationID is the current organization context (optional).
	OrganizationID *uuid.UUID `json:"org_id,omitempty"`

	// OrganizationSlug is the current organization slug (optional).
	OrganizationSlug string `json:"org_slug,omitempty"`

	// Role is the user's role in the current organization (optional).
	Role string `json:"role,omitempty"`

	// Permissions are fine-grained permissions (optional).
	Permissions []string `json:"perms,omitempty"`

	// IsPlatformAdmin indicates cross-organization admin access.
	IsPlatformAdmin bool `json:"platform_admin,omitempty"`

	// TokenType distinguishes access tokens from refresh tokens.
	TokenType TokenType `json:"type,omitempty"`

	// TokenFamily is used for refresh token rotation tracking.
	TokenFamily string `json:"family,omitempty"`

	// Confirmation contains the DPoP binding (cnf claim with jkt).
	// When set, the token is bound to a specific DPoP key pair.
	Confirmation *CNFClaim `json:"cnf,omitempty"`
}

Claims represents the CoreForge JWT claims structure. It embeds standard JWT claims and adds CoreForge-specific fields.

func NewAccessClaims

func NewAccessClaims(cfg *Config, userID uuid.UUID, email, name string) *Claims

NewAccessClaims creates claims for a new access token.

func NewRefreshClaims

func NewRefreshClaims(cfg *Config, userID uuid.UUID, family string) *Claims

NewRefreshClaims creates claims for a new refresh token.

func (*Claims) DPoPThumbprint

func (c *Claims) DPoPThumbprint() string

DPoPThumbprint returns the DPoP JWK thumbprint if the token is DPoP-bound. Returns empty string if not bound.

func (*Claims) IsAccessToken

func (c *Claims) IsAccessToken() bool

IsAccessToken returns true if this is an access token.

func (*Claims) IsDPoPBound

func (c *Claims) IsDPoPBound() bool

IsDPoPBound returns true if this token is bound to a DPoP key.

func (*Claims) IsExpired

func (c *Claims) IsExpired() bool

IsExpired returns true if the token has expired.

func (*Claims) IsRefreshToken

func (c *Claims) IsRefreshToken() bool

IsRefreshToken returns true if this is a refresh token.

func (*Claims) WithDPoPBinding

func (c *Claims) WithDPoPBinding(thumbprint string) *Claims

WithDPoPBinding adds DPoP binding to access token claims. The thumbprint should be computed using RFC 7638 (JWK thumbprint).

func (*Claims) WithOrganization

func (c *Claims) WithOrganization(orgID uuid.UUID, slug, role string, permissions []string) *Claims

WithOrganization adds organization context to the claims.

func (*Claims) WithPlatformAdmin

func (c *Claims) WithPlatformAdmin(isPlatformAdmin bool) *Claims

WithPlatformAdmin marks the user as a platform administrator.

type Config

type Config struct {
	// Secret is the symmetric key used for HS256 signing.
	// Either Secret or PrivateKey must be provided.
	Secret []byte //nolint:gosec // G117: field holds runtime secret value

	// PrivateKey is the RSA or ECDSA private key for RS256/ES256 signing.
	// Either Secret or PrivateKey must be provided.
	PrivateKey any

	// PublicKey is the RSA or ECDSA public key for RS256/ES256 verification.
	// Required when PrivateKey is set.
	PublicKey any

	// Algorithm specifies the signing algorithm.
	// Supported: HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512
	// Defaults to HS256.
	Algorithm string

	// Issuer is the JWT "iss" claim value.
	Issuer string

	// Audience is the JWT "aud" claim value.
	Audience []string

	// AccessTokenExpiry is the duration before access tokens expire.
	// Defaults to 15 minutes.
	AccessTokenExpiry time.Duration

	// RefreshTokenExpiry is the duration before refresh tokens expire.
	// Defaults to 7 days.
	RefreshTokenExpiry time.Duration

	// RefreshTokenRotation enables automatic refresh token rotation.
	// When enabled, a new refresh token is issued on each refresh.
	RefreshTokenRotation bool
}

Config holds JWT configuration options.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults. You must still provide a Secret or PrivateKey.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that the configuration is valid.

type DPoPBinding

type DPoPBinding struct {
	// Thumbprint is the JWK thumbprint of the DPoP key pair.
	Thumbprint string
}

DPoPBinding contains DPoP binding information for a token.

type Service

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

Service provides JWT token operations.

func NewService

func NewService(cfg *Config) (*Service, error)

NewService creates a new JWT service with the given configuration.

func (*Service) AccessTokenTTL

func (s *Service) AccessTokenTTL() time.Duration

AccessTokenTTL returns the access token expiry duration. This method provides compatibility with goauth/jwt.Service.

func (*Service) Config

func (s *Service) Config() *Config

Config returns the service configuration.

func (*Service) GenerateAccessToken

func (s *Service) GenerateAccessToken(userID uuid.UUID, email, name string) (string, error)

GenerateAccessToken creates a new access token for the given user.

func (*Service) GenerateAccessTokenWithOptions

func (s *Service) GenerateAccessTokenWithOptions(userID uuid.UUID, email, name string, opts TokenOptions) (string, error)

GenerateAccessTokenWithOptions creates a new access token with optional parameters.

func (*Service) GenerateAccessTokenWithOrg

func (s *Service) GenerateAccessTokenWithOrg(
	userID uuid.UUID,
	email, name string,
	orgID uuid.UUID,
	orgSlug, role string,
	permissions []string,
	isPlatformAdmin bool,
) (string, error)

GenerateAccessTokenWithOrg creates an access token with organization context.

func (*Service) GenerateAccessTokenWithOrgAndOptions

func (s *Service) GenerateAccessTokenWithOrgAndOptions(
	userID uuid.UUID,
	email, name string,
	orgID uuid.UUID,
	orgSlug, role string,
	permissions []string,
	isPlatformAdmin bool,
	opts TokenOptions,
) (string, error)

GenerateAccessTokenWithOrgAndOptions creates an access token with organization context and options.

func (*Service) GenerateRefreshToken

func (s *Service) GenerateRefreshToken(userID uuid.UUID, family string) (string, error)

GenerateRefreshToken creates a new refresh token for the given user. The family parameter is used for refresh token rotation tracking.

func (*Service) GenerateTokenPair

func (s *Service) GenerateTokenPair(userID uuid.UUID, email, name string) (*TokenPair, error)

GenerateTokenPair creates both an access token and refresh token.

func (*Service) GenerateTokenPairLegacy

func (s *Service) GenerateTokenPairLegacy(userID uuid.UUID, email string, isPlatformAdmin bool) (*TokenPair, error)

GenerateTokenPairLegacy creates a token pair using the legacy goauth interface. This provides backward compatibility during migration from goauth/jwt. Deprecated: Use GenerateTokenPair or GenerateTokenPairWithOrg instead.

func (*Service) GenerateTokenPairWithOptions

func (s *Service) GenerateTokenPairWithOptions(userID uuid.UUID, email, name string, opts TokenOptions) (*TokenPair, error)

GenerateTokenPairWithOptions creates a token pair with optional DPoP binding.

func (*Service) GenerateTokenPairWithOrg

func (s *Service) GenerateTokenPairWithOrg(
	userID uuid.UUID,
	email, name string,
	orgID uuid.UUID,
	orgSlug, role string,
	permissions []string,
	isPlatformAdmin bool,
) (*TokenPair, error)

GenerateTokenPairWithOrg creates a token pair with organization context.

func (*Service) RefreshTokenTTL

func (s *Service) RefreshTokenTTL() time.Duration

RefreshTokenTTL returns the refresh token expiry duration. This method provides compatibility with goauth/jwt.Service.

func (*Service) ValidateAccessToken

func (s *Service) ValidateAccessToken(tokenString string) (*Claims, error)

ValidateAccessToken validates and parses an access token.

func (*Service) ValidateRefreshToken

func (s *Service) ValidateRefreshToken(tokenString string) (*Claims, error)

ValidateRefreshToken validates and parses a refresh token.

type TokenOptions

type TokenOptions struct {
	// DPoPThumbprint binds the token to a DPoP key pair.
	// When set, the token will include a cnf.jkt claim.
	DPoPThumbprint string
}

TokenOptions contains optional parameters for token generation.

type TokenPair

type TokenPair struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"` // Access token expiry in seconds
}

TokenPair represents an access token and refresh token pair.

type TokenType

type TokenType string

TokenType identifies the type of token.

const (
	// AccessToken is a short-lived token for API access.
	AccessToken TokenType = "access"
	// RefreshToken is a long-lived token for obtaining new access tokens.
	RefreshToken TokenType = "refresh"
)

Jump to

Keyboard shortcuts

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