jwt

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package jwt implements the authenticator for the JWT auth mode

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrJWTAuthKeyRequired occurs when either JWT key or JWK URL is empty.
	ErrJWTAuthKeyRequired = errors.New("require either JWT key or JWK URL")
	// ErrJWKsURLRequired occurs when the JWK URL is empty.
	ErrJWKsURLRequired = errors.New("the JWK URL must not be empty")
	// ErrJWTClaimsConfigEmpty occurs when the JWT claims config is empty.
	ErrJWTClaimsConfigEmpty = errors.New(
		"invalid claims config. Require either namespace or locations",
	)
	// ErrJWTClaimsConfigInvalidLocation occurs when the location config of JWT claims is invalid.
	ErrJWTClaimsConfigInvalidLocation = errors.New("invalid claims location")
	// ErrJWTClaimsNull occurs when the JWT claims value is null.
	ErrJWTClaimsNull = errors.New("jwt claims data is null")
	// ErrJWTClaimsMalformedStringifyJSON occurs when the JWT claims value is not a JSON string.
	ErrJWTClaimsMalformedStringifyJSON = errors.New(
		"invalid jwt claims data: malformed stringify json",
	)
	// ErrJWTClaimsMalformedJSON occurs when the JWT claims value is not a JSON object.
	ErrJWTClaimsMalformedJSON = errors.New("invalid jwt claims data: malformed json object")
	// ErrInvalidJWTClaimsFormat occurs when the JWT claims format is invalid.
	ErrInvalidJWTClaimsFormat = fmt.Errorf(
		"invalid JWTClaimsFormat. Expected one of %v",
		GetSupportedJWTClaimsFormats(),
	)
	// ErrInvalidSignatureAlgorithm occurs when the JWT signature algorithm enum is invalid.
	ErrInvalidSignatureAlgorithm = fmt.Errorf(
		"invalid SignatureAlgorithm. Expected one of %v",
		GetSupportedSignatureAlgorithms(),
	)
	// ErrGetJWKsFailed occurs when failed to get JSON web keys from the remote URL.
	ErrGetJWKsFailed = errors.New("jwk: get keys failed")
	// ErrJWTVerificationFailed occurs when failed to verify the JWT auth token.
	ErrJWTVerificationFailed = errors.New("failed to verify jwt token signature")
	// ErrInvalidJWTKey occurs when the JWT key is invalid.
	ErrInvalidJWTKey = errors.New("invalid JWT key")
)

Functions

func Authenticate

Authenticate validates and authenticates the token from the auth webhook request.

func CloseJWKS

func CloseJWKS() error

CloseJWKS closes resources of the JWK store.

func GetJWKSCount

func GetJWKSCount() int

GetJWKSCount gets the current number of JWKS instances from the global store.

func GetSupportedSignatureAlgorithms

func GetSupportedSignatureAlgorithms() []jose.SignatureAlgorithm

GetSupportedSignatureAlgorithms get the list of supported signature algorithms for JSON Web Token.

func ParseSignatureAlgorithm

func ParseSignatureAlgorithm(value string) (jose.SignatureAlgorithm, error)

ParseSignatureAlgorithm parses a SignatureAlgorithm from string.

func ReloadJWKS

func ReloadJWKS(ctx context.Context) error

ReloadJWKS reloads all JSON Web Key Sets from the global store.

func ResetJWKStore

func ResetJWKStore()

ResetJWKStore clears all existing JSON web keys from the global store.

func UnregisterJWKS

func UnregisterJWKS(key string)

UnregisterJWKS removes a JSON web key set from the global store if exists.

Types

type HMACKey

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

HMACKey represents an HMAC secret key.

func NewHMACKey

func NewHMACKey(hmacKey []byte, algorithm jose.SignatureAlgorithm) *HMACKey

NewHMACKey creates a new HMAC secret key.

func (*HMACKey) Equal

func (hk *HMACKey) Equal(target SignatureVerifier) bool

Equal checks if the target value is equal.

func (*HMACKey) GetSignatureAlgorithms

func (hk *HMACKey) GetSignatureAlgorithms() []jose.SignatureAlgorithm

GetSignatureAlgorithms get signature algorithms of the keyset.

func (*HMACKey) VerifySignature

func (hk *HMACKey) VerifySignature(
	_ context.Context,
	sig *jose.JSONWebSignature,
) ([]byte, error)

VerifySignature compares a JWT signature against a static JWT secret key.

type JWKS

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

JWKS represents a JSON key set secret.

func RegisterJWKS

func RegisterJWKS(
	ctx context.Context,
	jwksURL string,
	options ...RegisterJWKSOption,
) (*JWKS, error)

RegisterJWKS registers a JWKS URL to the global store.

func (*JWKS) Equal

func (j *JWKS) Equal(target SignatureVerifier) bool

Equal checks if the target value is equal.

func (*JWKS) GetSignatureAlgorithms

func (j *JWKS) GetSignatureAlgorithms() []jose.SignatureAlgorithm

GetSignatureAlgorithms get signature algorithms of the keyset.

func (*JWKS) VerifySignature

func (j *JWKS) VerifySignature(
	ctx context.Context,
	jws *jose.JSONWebSignature,
) ([]byte, error)

VerifySignature verifies a JWT signature using cached and dynamically fetched JSON Web Keys (JWKS).

type JWKStore

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

JWKStore represents a global JWT store structure.

type JWTAuthenticator

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

JWTAuthenticator implements the authenticator with JWT key.

func NewJWTAuthenticator

func NewJWTAuthenticator(options authmode.RelyAuthenticatorOptions) *JWTAuthenticator

NewJWTAuthenticator creates a JWT authenticator instance.

func (*JWTAuthenticator) Add

func (ja *JWTAuthenticator) Add(
	ctx context.Context,
	config RelyAuthJWTConfig,
	securityRules *authmode.RelyAuthSecurityRules,
) error

Add a new JWT authenticator from config.

func (*JWTAuthenticator) Authenticate

Authenticate validates and authenticates the token from the auth webhook request.

func (*JWTAuthenticator) Close

func (ja *JWTAuthenticator) Close() error

Close handles the resources cleaning.

func (JWTAuthenticator) Equal

func (ja JWTAuthenticator) Equal(target JWTAuthenticator) bool

Equal checks if the target value is equal.

func (*JWTAuthenticator) IDs added in v0.0.2

func (ja *JWTAuthenticator) IDs() []string

IDs returns identities of this authenticator.

func (*JWTAuthenticator) Mode

Mode returns the auth mode of the current authenticator.

type JWTClaimsConfig

type JWTClaimsConfig struct {
	// Used when all of JWT claims are present in a single object within the decoded JWT.
	Namespace *JWTClaimsNamespace `json:"namespace,omitempty" yaml:"namespace,omitempty"`
	// Can be used when JWT claims are not all present in the single object,
	// but individual claims are provided a JSON pointer within the decoded JWT and optionally a default value.
	Locations map[string]jmes.FieldMappingEntryConfig `json:"locations,omitempty" yaml:"locations,omitempty"`
}

JWTClaimsConfig represents the claims config. Either specified via claims mappings or namespace.

func (JWTClaimsConfig) Equal

func (j JWTClaimsConfig) Equal(target JWTClaimsConfig) bool

Equal checks if the target value is equal.

func (JWTClaimsConfig) IsZero

func (j JWTClaimsConfig) IsZero() bool

IsZero if the current instance is empty.

func (JWTClaimsConfig) Validate

func (j JWTClaimsConfig) Validate() error

Validate if the current instance is valid.

type JWTClaimsFormat

type JWTClaimsFormat string

JWTClaimsFormat is the format in which JWT claims will be present.

const (
	// JWTClaimsFormatJSON the claims will be in the JSON format.
	JWTClaimsFormatJSON JWTClaimsFormat = "Json"
	// JWTClaimsFormatStringifiedJSON the claims will be in the Stringified JSON format.
	JWTClaimsFormatStringifiedJSON JWTClaimsFormat = "StringifiedJson"
)

func GetSupportedJWTClaimsFormats

func GetSupportedJWTClaimsFormats() []JWTClaimsFormat

GetSupportedJWTClaimsFormats get the list of supported JWT claims formats.

func ParseJWTClaimsFormat

func ParseJWTClaimsFormat(value string) (JWTClaimsFormat, error)

ParseJWTClaimsFormat parses a JWTClaimsFormat from string.

func (JWTClaimsFormat) Equal

func (j JWTClaimsFormat) Equal(target JWTClaimsFormat) bool

Equal checks if the target value is equal.

func (JWTClaimsFormat) IsZero

func (j JWTClaimsFormat) IsZero() bool

IsZero if the current instance is empty.

func (JWTClaimsFormat) JSONSchema

func (JWTClaimsFormat) JSONSchema() *jsonschema.Schema

JSONSchema defines a custom definition for JSON schema.

func (JWTClaimsFormat) Validate

func (j JWTClaimsFormat) Validate() error

Validate checks if the value is valid.

type JWTClaimsNamespace

type JWTClaimsNamespace struct {
	// Path to lookup the Hasura claims within the decoded claims.
	Location string `json:"location" yaml:"location"`
	// Format in which the Hasura claims will be present.
	ClaimsFormat JWTClaimsFormat `json:"claimsFormat" jsonschema:"enum=Json,enum=StringifiedJson" yaml:"claimsFormat"`
}

JWTClaimsNamespace is used when all of JWT claims are present in a single object within the decoded JWT.

func (JWTClaimsNamespace) Equal

func (j JWTClaimsNamespace) Equal(target JWTClaimsNamespace) bool

Equal checks if the target value is equal.

func (JWTClaimsNamespace) IsZero

func (j JWTClaimsNamespace) IsZero() bool

IsZero if the current instance is empty.

func (JWTClaimsNamespace) Validate

func (j JWTClaimsNamespace) Validate() error

Validate if the current instance is valid.

type JWTKey

type JWTKey struct {
	// Algorithm specifies the cryptographic signing algorithm which is used to sign the JWTs.
	// This is required only if you are using the key property in the config.
	Algorithm jose.SignatureAlgorithm `json:"algorithm,omitempty" yaml:"algorithm,omitempty"`
	// An URL where a provider publishes their JWKs (JSON Web Keys - which are used for signing the JWTs).
	// The URL must publish the JWKs in the standard format as described in the RFC 7517 specification.
	// This is optional as you have the alternative of also providing the key (certificate, PEM-encoded public key) as a string - in the key field along with the type.
	JWKFromURL *goenvconf.EnvString `json:"jwkFromUrl,omitempty" yaml:"jwkFromUrl,omitempty"`
	// Inline value of the key to use for decoding the JWT.
	Key *goenvconf.EnvString `json:"key,omitempty" yaml:"key,omitempty"`
}

JWTKey holds the information of the JWT key to verify the token.

func (JWTKey) Equal

func (j JWTKey) Equal(target JWTKey) bool

Equal checks if the target value is equal.

func (JWTKey) IsZero

func (j JWTKey) IsZero() bool

IsZero if the current instance is empty.

func (JWTKey) JSONSchema

func (JWTKey) JSONSchema() *jsonschema.Schema

JSONSchema defines a custom definition for JSON schema.

func (JWTKey) Validate

func (j JWTKey) Validate() error

Validate if the current instance is valid.

type JWTKeySet

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

JWTKeySet is a verifier that validates JWT against a static set of HMAC or public keys.

func NewJWTKeySet

func NewJWTKeySet(
	ctx context.Context,
	config *RelyAuthJWTConfig,
	securityRules *authmode.RelyAuthSecurityRules,
	options authmode.RelyAuthenticatorOptions,
) (*JWTKeySet, error)

NewJWTKeySet creates a new JWT key set from the configuration.

func (*JWTKeySet) Close

func (*JWTKeySet) Close() error

Close handles the resources cleaning.

func (*JWTKeySet) Equal

func (j *JWTKeySet) Equal(target *JWTKeySet) bool

Equal checks if the target value is equal.

func (*JWTKeySet) GetConfig

func (j *JWTKeySet) GetConfig() *RelyAuthJWTConfig

GetConfig get config of the current keyset.

func (*JWTKeySet) GetSignatureAlgorithms

func (j *JWTKeySet) GetSignatureAlgorithms() []jose.SignatureAlgorithm

GetSignatureAlgorithms get signature algorithms of the keyset.

func (*JWTKeySet) TransformClaims

func (j *JWTKeySet) TransformClaims(rawBytes []byte, desiredRole string) (map[string]any, error)

TransformClaims transform JWT claims to expected session variables.

func (*JWTKeySet) ValidateClaims

func (j *JWTKeySet) ValidateClaims(claims *jwt.Claims) error

ValidateClaims checks claims in a token against expected values.

func (*JWTKeySet) ValidateSecurityRules added in v0.0.2

func (j *JWTKeySet) ValidateSecurityRules(body *authmode.AuthenticateRequestData) error

ValidateSecurityRules validates security rules of the current JWT key set config.

func (*JWTKeySet) VerifySignature

func (j *JWTKeySet) VerifySignature(
	ctx context.Context,
	sig *jose.JSONWebSignature,
) ([]byte, error)

VerifySignature verifies a JWT signature using the configured signature verifier.

type PublicKey

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

PublicKey represents a public key to verify signatures.

func NewPublicKey

func NewPublicKey(publicKey crypto.PublicKey, algorithm jose.SignatureAlgorithm) *PublicKey

NewPublicKey creates a new public key.

func (*PublicKey) Equal

func (pk *PublicKey) Equal(target SignatureVerifier) bool

Equal checks if the target value is equal.

func (*PublicKey) GetSignatureAlgorithms

func (pk *PublicKey) GetSignatureAlgorithms() []jose.SignatureAlgorithm

GetSignatureAlgorithms get signature algorithms of the keyset.

func (*PublicKey) VerifySignature

func (pk *PublicKey) VerifySignature(
	_ context.Context,
	sig *jose.JSONWebSignature,
) ([]byte, error)

VerifySignature compares a JWT signature against a static JWT public key.

type RegisterJWKSOption

type RegisterJWKSOption func(*RegisterJWKSOptions)

RegisterJWKSOption abstracts a function to modify RegisterJWKSOptions.

func RegisterJWKSWithHTTPClient

func RegisterJWKSWithHTTPClient(httpClient *gohttpc.Client) RegisterJWKSOption

RegisterJWKSWithHTTPClient returns a function to set the HTTP client.

func RegisterJWKSWithPrefix

func RegisterJWKSWithPrefix(prefix string) RegisterJWKSOption

RegisterJWKSWithPrefix returns a function to set the prefix.

type RegisterJWKSOptions

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

RegisterJWKSOptions holds options for registering JWKS.

type RelyAuthJWTConfig

type RelyAuthJWTConfig struct {
	// Unique identity of the auth config.
	// If not set, ID will be the index of the array.
	ID string `json:"id,omitempty" yaml:"id,omitempty"`
	// Authentication mode which is always jwt.
	Mode authmode.AuthMode `json:"mode" jsonschema:"enum=jwt" yaml:"mode"`
	// Brief description of the auth config.
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	// Validation to check that the aud field is a member of the audience received, otherwise will throw error.
	// Required if there are many JWT auth configurations.
	Audience []string `json:"audience,omitempty" yaml:"audience,omitempty"`
	// Validation to check that the iss field is a member of the iss received, otherwise will throw error.
	// Required if there are many JWT auth configurations.
	Issuer string `json:"issuer,omitempty" yaml:"issuer,omitempty"`
	// The allowed leeway (in seconds) to the exp validation to account for clock skew.
	AllowedSkew int `json:"allowedSkew,omitempty" yaml:"allowedSkew,omitempty"`
	// Source of the JWT authentication token.
	TokenLocation authscheme.TokenLocation `json:"tokenLocation" yaml:"tokenLocation"`
	// Information of the JWT key to verify the token.
	Key JWTKey `json:"key" yaml:"key"`
	// Configuration to describe how and where the engine should look for the claims within the decoded token.
	// You can vary the format and location of the claims.
	ClaimsConfig JWTClaimsConfig `json:"claimsConfig" yaml:"claimsConfig"`
}

RelyAuthJWTConfig according to which the incoming JWT will be verified and decoded to extract the session variable claims.

func NewRelyAuthJWTConfig

func NewRelyAuthJWTConfig(key JWTKey, tokenLocation authscheme.TokenLocation) *RelyAuthJWTConfig

NewRelyAuthJWTConfig creates a new JWTAuthDefinition instance.

func (RelyAuthJWTConfig) Equal

func (j RelyAuthJWTConfig) Equal(target RelyAuthJWTConfig) bool

Equal checks if the target value is equal.

func (RelyAuthJWTConfig) GetMode

GetMode returns the auth mode of the current config.

func (RelyAuthJWTConfig) IsZero

func (j RelyAuthJWTConfig) IsZero() bool

IsZero if the current instance is empty.

func (RelyAuthJWTConfig) Validate

func (j RelyAuthJWTConfig) Validate() error

Validate if the current instance is valid.

type SignatureVerifier

type SignatureVerifier interface {
	// GetSignatureAlgorithms get signature algorithms of the keyset.
	GetSignatureAlgorithms() []jose.SignatureAlgorithm
	// VerifySignature verifies a JWT signature using the configured verification method.
	VerifySignature(ctx context.Context, sig *jose.JSONWebSignature) ([]byte, error)
	// Equal checks if the target value is equal.
	Equal(target SignatureVerifier) bool
}

SignatureVerifier abstracts an interface to verify JSON web signatures.

func NewStaticKey

func NewStaticKey(
	rawKey []byte,
	algorithm jose.SignatureAlgorithm,
) (SignatureVerifier, error)

NewStaticKey creates a JWT secret from static credentials.

Jump to

Keyboard shortcuts

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