jwt

package
v0.19.156 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: Apache-2.0 Imports: 29 Imported by: 7

Documentation

Index

Constants

View Source
const (
	// DefaultNotBefore offset for NotBefore
	DefaultNotBefore = -2 * time.Minute
)

Variables

View Source
var (
	// TimeNowFn to override in unit tests
	TimeNowFn = time.Now

	// DefaultTimeSkew is an interval for allowed time skew
	DefaultTimeSkew = 5 * time.Minute
)

Functions

func CopyUserInfoClaims added in v0.2.0

func CopyUserInfoClaims(src, dst MapClaims)

CopyUserInfoClaims from source to destination

func DecodeSegment added in v0.2.0

func DecodeSegment(seg string) ([]byte, error)

DecodeSegment JWT specific base64url encoding with padding stripped

func EncodeSegment

func EncodeSegment(seg []byte) string

EncodeSegment returns JWT specific base64url encoding with padding stripped

func SetClaimsExpiration added in v0.2.0

func SetClaimsExpiration(claims MapClaims, expiry time.Duration)

SetClaimsExpiration sets expiration claims

func VerifySignature added in v0.2.0

func VerifySignature(algo, signingString, signature string, key any) error

VerifySignature returns error if JWT signature is invalid

Types

type Audience added in v0.2.0

type Audience []string

Audience represents the recipients that the token is intended for.

func (Audience) Contains added in v0.2.0

func (s Audience) Contains(expected string) bool

Contains returns true if audience contains expected value

func (*Audience) UnmarshalJSON added in v0.2.0

func (s *Audience) UnmarshalJSON(b []byte) error

UnmarshalJSON reads an audience from its JSON representation.

type Claims

type Claims struct {
	Issuer    string       `json:"iss,omitempty"`
	Subject   string       `json:"sub,omitempty"`
	Audience  Audience     `json:"aud,omitempty"`
	Expiry    *NumericDate `json:"exp,omitempty"`
	NotBefore *NumericDate `json:"nbf,omitempty"`
	IssuedAt  *NumericDate `json:"iat,omitempty"`
	ID        string       `json:"jti,omitempty"`

	// DPoP specific claims
	Cnf        *Cnf   `json:"cnf,omitempty"`
	Nonce      string `json:"nonce,omitempty"`
	HTTPMethod string `json:"htm,omitempty"`
	HTTPUri    string `json:"htu,omitempty"`

	// Custom most common claims
	Name          string `json:"name,omitempty"`
	Profile       string `json:"profile ,omitempty"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified ,omitempty"`
	Phone         string `json:"phone_number,omitempty"`
	PhoneVerified bool   `json:"phone_number_verified ,omitempty"`
	// Role in the service
	Role   string `json:"role,omitempty"`
	Tenant string `json:"tenant,omitempty"`
	Org    string `json:"org,omitempty"`
	// map of Org:Role
	Orgs    map[string]string `json:"orgs,omitempty"`
	OrgRole string            `json:"org_role,omitempty"`
}

Claims represents public claim values (as specified in RFC 7519).

func (*Claims) Marshal

func (c *Claims) Marshal() string

Marshal returns JSON encoded string

func (*Claims) Valid

func (c *Claims) Valid(cfg *VerifyConfig) error

Valid returns error if the standard claims are invalid

func (*Claims) VerifyAudience added in v0.2.0

func (c *Claims) VerifyAudience(expected []string) error

VerifyAudience compares the aud claim against expected.

func (*Claims) VerifyExpiresAt added in v0.2.0

func (c *Claims) VerifyExpiresAt(now time.Time, req bool) error

VerifyExpiresAt returns true issued at is valid.

func (*Claims) VerifyIssuedAt added in v0.2.0

func (c *Claims) VerifyIssuedAt(now time.Time, req bool) error

VerifyIssuedAt verifies the iat claim.

func (*Claims) VerifyIssuer added in v0.2.0

func (c *Claims) VerifyIssuer(expected string) error

VerifyIssuer compares the iss claim against expected.

func (*Claims) VerifyNotBefore added in v0.2.0

func (c *Claims) VerifyNotBefore(now time.Time, req bool) error

VerifyNotBefore verifies the nbf claim.

func (*Claims) VerifySubject added in v0.2.0

func (c *Claims) VerifySubject(expected string) error

VerifySubject compares the sub claim against expected.

type Cnf added in v0.5.0

type Cnf struct {
	Jkt string `json:"jkt,omitempty"`
}

Cnf is DPoP specific claim for JWT Key ID

type Key

type Key struct {
	// ID of the key
	ID   string `json:"id" yaml:"id"`
	Seed string `json:"seed" yaml:"seed"`
}

Key for JWT signature

type KeySet added in v0.10.0

type KeySet interface {
	GetKey(ctx context.Context, kid string) (any, error)
}

KeySet is an interface for verifying JWT signatures.

type Keyfunc added in v0.2.0

type Keyfunc func(*Token) (any, error)

Keyfunc is a callback function to supply the key for verification. The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as `kid`) to identify which key to use.

type MapClaims added in v0.2.0

type MapClaims map[string]any

MapClaims provides generic claims on map

func CreateClaims added in v0.2.0

func CreateClaims(jti, subject, issuer string, audience []string, expiry time.Duration, extraClaims MapClaims) MapClaims

CreateClaims returns claims

func (MapClaims) Add added in v0.2.0

func (c MapClaims) Add(val ...any) error

Add new claims to the map

func (MapClaims) Bool added in v0.2.0

func (c MapClaims) Bool(k string) bool

Bool will return the named claim as Bool

func (MapClaims) CNF added in v0.5.0

func (c MapClaims) CNF() *Cnf

CNF returns DPoP cnf claim

func (MapClaims) Int added in v0.2.0

func (c MapClaims) Int(k string) int

Int will return the named claim as an int

func (MapClaims) Int64 added in v0.3.0

func (c MapClaims) Int64(k string) int64

Int64 will return the named claim as an int64

func (MapClaims) Marshal added in v0.2.0

func (c MapClaims) Marshal() string

Marshal returns JSON encoded string

func (MapClaims) String added in v0.2.0

func (c MapClaims) String(k string) string

String will return the named claim as a string, if the underlying type is not a string, it will try and co-oerce it to a string.

func (MapClaims) StringsMap added in v0.5.0

func (c MapClaims) StringsMap(k string) map[string]string

StringsMap will return the named claim as a map[string]string,

func (MapClaims) Time added in v0.2.0

func (c MapClaims) Time(k string) *time.Time

Time will return the named claim as Time pointer

func (MapClaims) TimeVal added in v0.5.0

func (c MapClaims) TimeVal(k string) time.Time

TimeVal will return the named claim as Time value

func (MapClaims) To added in v0.2.0

func (c MapClaims) To(val any) error

To converts the claims to the value pointed to by v.

func (MapClaims) UInt64 added in v0.3.0

func (c MapClaims) UInt64(k string) uint64

UInt64 will return the named claim as an uint64

func (MapClaims) Valid added in v0.2.0

func (c MapClaims) Valid(cfg *VerifyConfig) error

Valid returns error if the standard claims are invalid

func (MapClaims) VerifyAudience added in v0.2.0

func (c MapClaims) VerifyAudience(expected []string) error

VerifyAudience compares the aud claim against expected.

func (MapClaims) VerifyExpiresAt added in v0.2.0

func (c MapClaims) VerifyExpiresAt(now time.Time, req bool) error

VerifyExpiresAt returns true issued at is valid.

func (MapClaims) VerifyIssuedAt added in v0.2.0

func (c MapClaims) VerifyIssuedAt(now time.Time, req bool) error

VerifyIssuedAt verifies the iat claim.

func (MapClaims) VerifyIssuer added in v0.2.0

func (c MapClaims) VerifyIssuer(expected string) error

VerifyIssuer compares the iss claim against expected.

func (MapClaims) VerifyNotBefore added in v0.2.0

func (c MapClaims) VerifyNotBefore(now time.Time, req bool) error

VerifyNotBefore verifies the nbf claim.

func (MapClaims) VerifySubject added in v0.2.0

func (c MapClaims) VerifySubject(expected string) error

VerifySubject compares the sub claim against expected.

type NumericDate added in v0.2.0

type NumericDate int64

NumericDate represents date and time as the number of seconds since the epoch, ignoring leap seconds. Non-integer values can be represented in the serialized format, but we round to the nearest second. See RFC7519 Section 2: https://tools.ietf.org/html/rfc7519#section-2

func NewNumericDate added in v0.2.0

func NewNumericDate(t time.Time) *NumericDate

NewNumericDate constructs NumericDate from time.Time value.

func (NumericDate) MarshalJSON added in v0.2.0

func (n NumericDate) MarshalJSON() ([]byte, error)

MarshalJSON serializes the given NumericDate into its JSON representation.

func (*NumericDate) Time added in v0.2.0

func (n *NumericDate) Time() time.Time

Time returns time.Time representation of NumericDate.

func (*NumericDate) UnmarshalJSON added in v0.2.0

func (n *NumericDate) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a date from its JSON representation.

type Option

type Option interface {
	// contains filtered or unexported methods
}

A Option modifies the default behavior of Provider.

func WithHeaders

func WithHeaders(headers map[string]any) Option

WithHeaders allows to specify extra headers or override defaults

type Parser

type Parser interface {
	// ParseToken returns jwt.StandardClaims
	ParseToken(ctx context.Context, authorization string, cfg *VerifyConfig) (MapClaims, error)
}

Parser specifies JWT parser interface

func NewParser added in v0.10.0

func NewParser(cfg *ParserConfig) (Parser, error)

NewParser returns Parser

type ParserConfig added in v0.10.0

type ParserConfig struct {
	// Issuer specifies issuer claim
	Issuer   string              `json:"issuer" yaml:"issuer"`
	JWKSURI  string              `json:"jwks_uri" yaml:"jwks_uri"`
	JWKeySet *jose.JSONWebKeySet `json:"jwks" yaml:"jwks"`
}

ParserConfig provides JWT parser configuration

func LoadParserConfig added in v0.10.0

func LoadParserConfig(file string) (*ParserConfig, error)

LoadParserConfig returns parser configuration loaded from a file

type Provider

type Provider interface {
	Signer
	Parser
}

Provider specifies JWT provider interface

func LoadProvider added in v0.10.0

func LoadProvider(cfgfile string, crypto *cryptoprov.Crypto) (Provider, error)

LoadProvider returns new provider

func MustNewProvider added in v0.10.0

func MustNewProvider(cfg *ProviderConfig, crypto *cryptoprov.Crypto, ops ...Option) Provider

MustNewProvider returns new provider

func NewProvider added in v0.10.0

func NewProvider(cfg *ProviderConfig, crypto *cryptoprov.Crypto, ops ...Option) (Provider, error)

NewProvider returns new provider that supports, both Signer and Parser

func NewProviderFromCryptoSigner added in v0.10.0

func NewProviderFromCryptoSigner(signer crypto.Signer, ops ...Option) (Provider, error)

NewProviderFromCryptoSigner returns new from Signer

func NewProviderWithSymmetricKey added in v0.16.0

func NewProviderWithSymmetricKey(key []byte, ops ...Option) (Provider, error)

NewProviderWithSymmetricKey returns new from Signer

type ProviderConfig added in v0.10.0

type ProviderConfig struct {
	// Issuer specifies issuer claim
	Issuer string `json:"issuer" yaml:"issuer"`
	// KeyID specifies ID of the current key
	KeyID string `json:"kid" yaml:"kid"`
	// Keys specifies list of issuer's keys
	Keys []*Key `json:"keys" yaml:"keys"`

	PrivateKey string `json:"private_key" yaml:"private_key"`

	// TokenExpiry specifies token expiration period
	TokenExpiry csr.Duration `json:"token_expiry" yaml:"token_expiry"`
}

ProviderConfig provides OAuth2 configuration

func LoadProviderConfig added in v0.10.0

func LoadProviderConfig(file string) (*ProviderConfig, error)

LoadProviderConfig returns provider configuration loaded from a file

type RemoteKeySet added in v0.10.0

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

RemoteKeySet is a KeySet implementation that validates JSON web tokens against a jwks_uri endpoint.

func NewRemoteKeySet added in v0.10.0

func NewRemoteKeySet(ctx context.Context, jwksURL string) *RemoteKeySet

NewRemoteKeySet returns a KeySet that can validate JSON web tokens by using HTTP GETs to fetch JSON web token sets hosted at a remote URL. This is automatically used by NewProvider using the URLs returned by OpenID Connect discovery, but is exposed for providers that don't support discovery or to prevent round trips to the discovery URL.

The returned KeySet is a long lived verifier that caches keys based on any keys change. Reuse a common remote key set instead of creating new ones as needed.

func (*RemoteKeySet) GetKey added in v0.10.0

func (r *RemoteKeySet) GetKey(ctx context.Context, keyID string) (any, error)

GetKey returns the public key for the given kid.

type Signer

type Signer interface {
	// SignClaims returns signed JWT token
	Sign(ctx context.Context, claims MapClaims) (string, error)
	// PublicKey is returned for assymetric signer
	PublicKey() crypto.PublicKey
	// Issuer returns name of the issuer
	Issuer() string
	// TokenExpiry specifies token expiration period
	TokenExpiry() time.Duration
}

Signer specifies JWT signer interface

type SignerInfo

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

SignerInfo represents JWT signer

func NewSignerInfo

func NewSignerInfo(signer crypto.Signer) (*SignerInfo, error)

NewSignerInfo returns *SignerInfo

type StaticKeySet added in v0.10.0

type StaticKeySet struct {
	// PublicKeys used to verify the JWT. Supported types are *rsa.PublicKey and
	// *ecdsa.PublicKey.
	PublicKeys []crypto.PublicKey
	KeySet     []jose.JSONWebKey
}

StaticKeySet is a verifier that validates JWT against a static set of public keys.

func (*StaticKeySet) GetKey added in v0.10.0

func (s *StaticKeySet) GetKey(ctx context.Context, keyID string) (any, error)

GetKey returns the public key for the given kid.

type Token added in v0.2.0

type Token struct {
	Raw           string         // The raw token.  Populated when you Parse a token
	SigningMethod string         // The signing method used or to be used
	Header        map[string]any // The first segment of the token
	Claims        ValidClaims    // The second segment of the token
	Signature     string         // The third segment of the token.  Populated when you Parse a token
	Valid         bool           // Is the token valid?  Populated when you Parse/Verify a token
}

Token for JWT

type TokenParser added in v0.2.0

type TokenParser struct {
	ValidMethods         []string // If populated, only these methods will be considered valid
	UseJSONNumber        bool     // Use JSON Number format in JSON decoder
	SkipClaimsValidation bool     // Skip claims validation during token parsing
}

TokenParser config

func (*TokenParser) Parse added in v0.2.0

func (p *TokenParser) Parse(tokenString string, cfg *VerifyConfig, keyFunc Keyfunc) (*Token, error)

Parse parses and validates JWT, and return a token. keyFunc will receive the parsed token and should return the key for validating. If everything is kosher, err will be nil

func (*TokenParser) ParseUnverified added in v0.2.0

func (p *TokenParser) ParseUnverified(tokenString string, claims MapClaims) (token *Token, parts []string, err error)

ParseUnverified parses the token but doesn't validate the signature. It's only ever useful in cases where you know the signature is valid (because it has been checked previously in the stack) and you want to extract values from it. WARNING: Don't use this method unless you know what you're doing

func (*TokenParser) ParseWithClaims added in v0.2.0

func (p *TokenParser) ParseWithClaims(tokenString string, cfg *VerifyConfig, claims MapClaims, keyFunc Keyfunc) (*Token, error)

ParseWithClaims parses token with a specified Claims

type ValidClaims added in v0.2.0

type ValidClaims interface {
	Valid(cfg *VerifyConfig) error
}

ValidClaims interface for Claims validation

type VerifyConfig

type VerifyConfig struct {
	// ExpectedIssuer validates the iss claim of a JWT matches this value
	ExpectedIssuer string
	// ExpectedSubject validates the sub claim of a JWT matches this value
	ExpectedSubject string
	// ExpectedAudience validates that the aud claim of a JWT contains this value
	ExpectedAudience []string
}

VerifyConfig expreses the possible options for validating a JWT

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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