Help us shape the future of Go! Take the 2026 Go Developer Survey

jwt

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	PrincipalTypeHuman       = "human"
	PrincipalTypeApplication = "application"
	PrincipalTypeAgent       = "agent"
	PrincipalTypeService     = "service"
)

Principal type constants for the PrincipalType field.

View Source
const (
	// AudienceBFF is the audience for BFF (web browser) clients.
	// These tokens are used for cookie-based sessions.
	AudienceBFF = "bff"
	// AudienceAPI is the audience for programmatic API clients.
	// These tokens are used with Bearer authentication and require scopes.
	AudienceAPI = "api"
)

Audience constants for different token types.

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")
	// ErrAudienceMismatch is returned when the token audience doesn't match expected value.
	ErrAudienceMismatch = errors.New("audience mismatch")
	// ErrScopesRequired is returned when API tokens are created without scopes.
	ErrScopesRequired = errors.New("at least one scope is required for API tokens")
)

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

	// PrincipalID is the unique identifier for the authenticated principal.
	PrincipalID uuid.UUID `json:"pid,omitempty"`

	// PrincipalType is the type of principal (human, application, agent, service).
	// Empty string defaults to "human" for backward compatibility.
	PrincipalType string `json:"pty,omitempty"`

	// Email is the principal's email address (primarily for human principals).
	Email string `json:"email,omitempty"`

	// Name is the principal'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 principal's role in the current organization (optional).
	Role string `json:"role,omitempty"`

	// ClientID is the OAuth client/application ID that obtained this token.
	// This is the "azp" (authorized party) claim from OAuth 2.0.
	// Used for per-application rate limiting and audit logging.
	ClientID string `json:"azp,omitempty"`

	// Scopes are the OAuth scopes granted to this token.
	Scopes []string `json:"scp,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 SystemForge JWT claims structure. It embeds standard JWT claims and adds SystemForge-specific fields.

func NewAccessClaims

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

NewAccessClaims creates claims for a new access token.

func NewRefreshClaims

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

NewRefreshClaims creates claims for a new refresh token.

func (*Claims) Audience

func (c *Claims) Audience() string

Audience returns the first audience value, or empty string if none.

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) HasAudience

func (c *Claims) HasAudience(aud string) bool

HasAudience checks if the claims include a specific audience.

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) WithAudience

func (c *Claims) WithAudience(audiences ...string) *Claims

WithAudience sets the audience claim (builder pattern). This overrides any audience set from Config.

func (*Claims) WithClientID

func (c *Claims) WithClientID(clientID string) *Claims

WithClientID sets the OAuth client/application ID (azp claim).

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.

func (*Claims) WithPrincipalType

func (c *Claims) WithPrincipalType(principalType string) *Claims

WithPrincipalType sets the principal type on the claims.

func (*Claims) WithScopes

func (c *Claims) WithScopes(scopes []string) *Claims

WithScopes sets the OAuth scopes on the claims.

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) GenerateAPIToken

func (s *Service) GenerateAPIToken(
	principalID uuid.UUID,
	email, name string,
	scopes []string,
	duration time.Duration,
) (string, error)

GenerateAPIToken creates a scoped token for API clients. API tokens require at least one scope. Duration overrides the default access token expiry if positive.

func (*Service) GenerateAccessToken

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

GenerateAccessToken creates a new access token for the given principal.

func (*Service) GenerateAccessTokenWithAudience

func (s *Service) GenerateAccessTokenWithAudience(
	principalID uuid.UUID,
	email, name string,
	audience string,
	scopes []string,
) (string, error)

GenerateAccessTokenWithAudience creates an access token with explicit audience.

func (*Service) GenerateAccessTokenWithOptions

func (s *Service) GenerateAccessTokenWithOptions(principalID 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(
	principalID 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(
	principalID 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) GenerateBFFTokenPair

func (s *Service) GenerateBFFTokenPair(principalID uuid.UUID, email, name string) (*TokenPair, error)

GenerateBFFTokenPair creates a token pair for BFF (web) clients. BFF tokens use cookie-based sessions and don't include scopes.

func (*Service) GenerateRefreshToken

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

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

func (*Service) GenerateTokenPair

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

GenerateTokenPair creates both an access token and refresh token.

func (*Service) GenerateTokenPairLegacy

func (s *Service) GenerateTokenPairLegacy(principalID 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) GenerateTokenPairWithAudience

func (s *Service) GenerateTokenPairWithAudience(
	principalID uuid.UUID,
	email, name string,
	audience string,
	scopes []string,
) (*TokenPair, error)

GenerateTokenPairWithAudience creates a token pair with explicit audience.

func (*Service) GenerateTokenPairWithOptions

func (s *Service) GenerateTokenPairWithOptions(principalID 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(
	principalID 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) ValidateAccessTokenForAudience added in v0.14.0

func (s *Service) ValidateAccessTokenForAudience(tokenString string, audiences ...string) (*Claims, error)

ValidateAccessTokenForAudience is ValidateAccessToken for a verifier that serves one kind of client: the token must be addressed to one of the audiences (AudienceBFF, AudienceAPI, or an application's own). A token minted for another audience, for example a narrowly scoped API token, is refused with ErrAudienceMismatch rather than accepted as a full session.

func (*Service) ValidateAccessTokenWithAudience

func (s *Service) ValidateAccessTokenWithAudience(tokenString string, expectedAudience string) (*Claims, error)

ValidateAccessTokenWithAudience validates an access token and checks expected audience. If expectedAudience is empty, audience checking is skipped (backward compatible).

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

	// Audience replaces the configured audience on this token, for example to
	// address it to one application when several share a signing key.
	Audience []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