jwt

package
v0.0.0-...-fbe9a17 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2022 License: Apache-2.0 Imports: 21 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMustEncodeFirst     = errors.New("must encode token first")
	ErrMissingPrivateKey   = errors.New("missing private key")
	ErrMissingPublicKey    = errors.New("missing public key")
	ErrMissingSymmetricKey = errors.New("missing symmetric key")
)

Token errors

View Source
var (
	ErrUnsignedToken        = errors.New("unsigned tokens not allowed")
	ErrInvalidJWTFormat     = errors.New("invalid JWT format")
	ErrInvalidHeaderFormat  = errors.New("invalid header format")
	ErrInvalidPayloadFormat = errors.New("invalid payload format")
	ErrMismatchedAlgorithms = errors.New("algorithms do not match between key and token")
	ErrMismatchedKeyID      = errors.New("key id does not match between token and key")
	ErrInvalidSignature     = errors.New("invalid signature")
)

Common JWT processing errors

Functions

This section is empty.

Types

type Algorithm

type Algorithm string

Algorithm is the specific algorithm with which to encode the JWT.

const (
	AlgorithmHMACSHA256  Algorithm = "HS256" // required, HMAC using SHA-256
	AlgorithmHMACSHA384  Algorithm = "HS384" // optional, HMAC using SHA-384
	AlgorithmHMACSHA512  Algorithm = "HS512" // optional, HMAC using SHA-512
	AlgorithmRSASHA256   Algorithm = "RS256" // recommended, RRSASSA-PKCS1-v1_5 using SHA-256
	AlgorithmRSASHA384   Algorithm = "RS384" // optional, RRSASSA-PKCS1-v1_5 using SHA-384
	AlgorithmRSASHA512   Algorithm = "RS512" // optional, RRSASSA-PKCS1-v1_5 using SHA-512
	AlgorithmECDSASHA256 Algorithm = "ES256" // recommended+, ECDSA using P-256 and SHA-256
	AlgorithmECDSASHA384 Algorithm = "ES384" // optional, ECDSA using P-384 and SHA-384
	AlgorithmECDSASHA512 Algorithm = "ES512" // optional, ECDSA using P-512 and SHA-512
	AlgorithmPSSSHA256   Algorithm = "PS256" // optional, RSASSA-PSS using SHA-256 and MGF1 with SHA-256
	AlgorithmPSSSHA384   Algorithm = "PS384" // optional, RSASSA-PSS using SHA-384 and MGF1 with SHA-384
	AlgorithmPSSSHA512   Algorithm = "PS512" // optional, RSASSA-PSS using SHA-512 and MGF1 with SHA-512
	AlgorithmNone        Algorithm = "none"  // optional, No digital signature or MAC performed
)

Valid Algorithm values as defined by RFC 7518

func (Algorithm) IsSymmetric

func (alg Algorithm) IsSymmetric() bool

IsSymmetric returns true for symmetric key-based algorithms.

func (Algorithm) IsValid

func (alg Algorithm) IsValid() error

IsValid returns true if the algorithm is supported

func (Algorithm) ValidForKeyType

func (alg Algorithm) ValidForKeyType(kt KeyType) bool

ValidForKeyType returns true if the algorithm and key type can be used together.

type Claims

type Claims struct {
	Issuer         string             `mapstructure:"iss,omitempty" json:"iss,omitempty"` // Required
	Subject        string             `mapstructure:"sub,omitempty" json:"sub,omitempty"` // Required
	Audience       string             `mapstructure:"aud,omitempty" json:"aud,omitempty"` // Required
	ExpirationTime int64              `mapstructure:"exp,omitempty" json:"exp,omitempty"` // Required for non-DPoP tokens
	NotBefore      int64              `mapstructure:"nbf,omitempty" json:"nbf,omitempty"`
	IssuedAt       int64              `mapstructure:"iat,omitempty" json:"iat,omitempty"` // Required
	JwtID          string             `mapstructure:"jti,omitempty" json:"jti,omitempty"` // Required for DPoP tokens
	Nonce          string             `mapstructure:"nonce,omitempty" json:"nonce,omitempty"`
	Confirmation   *ConfirmationClaim `mapstructure:"cnf,omitempty" json:"cnf,omitempty"`
	Scope          string             `mapstructure:"scope,omitempty" json:"scope,omitempty"` // Required for non-DPoP tokens

	// DPoP claims
	HTTPMethod string `mapstructure:"htm,omitempty" json:"htm,omitempty"` // The HTTP method for the request to which the JWT is attached
	HTTPURI    string `mapstructure:"htu,omitempty" json:"htu,omitempty"` // The HTTP URI used for the request, without query and fragment parts

	CustomClaims CustomClaims `mapstructure:",remain" json:"-"`
}

Claims holds all the claims this token provides.

func (*Claims) IsValid

func (c *Claims) IsValid(typ Type) error

IsValid checks whether the payload contains all required fields and is properly formatted. Returns an error if not.

type ConfirmationClaim

type ConfirmationClaim struct {
	JWK              *Key   `mapstructure:"jwk,omitempty" json:"jwk,omitempty"`
	SHA256Thumbprint string `mapstructure:"jkt,omitempty" json:"jkt,omitempty"`
}

ConfirmationClaim holds public key information for cryptographically verifying a sender holds the corresponding private key.

type CustomClaims

type CustomClaims map[string]interface{}

CustomClaims holds custom claims information outside the registered claims fields.

type EllipticCurve

type EllipticCurve string

EllipticCurve is the curve to use for elliptic curve public keys

const (
	EllipticCurveP256 EllipticCurve = "P-256"
	EllipticCurveP384 EllipticCurve = "P-384"
	EllipticCurveP521 EllipticCurve = "P-521"
)

Valid EllipticCurve values per RFC 7518

func (EllipticCurve) IsValid

func (crv EllipticCurve) IsValid() bool

IsValid returns true if the curve is supported

type Header struct {
	Type        Type   `json:"typ,omitempty"` // JWT or dpop+jwt
	ContentType string `json:"cty,omitempty"`

	// JWS Headers (will be different for JWE)
	Algorithm                      Algorithm `json:"alg,omitempty"` // Required
	JWKSetURL                      string    `json:"jwu,omitempty"`
	JWK                            *Key      `json:"jwk,omitempty"` // Required for DPoP tokens
	KeyID                          string    `json:"kid,omitempty"`
	X509URL                        string    `json:"x5u,omitempty"`
	X509CertificateChain           []string  `json:"x5c,omitempty"`
	X509CertificateSHA1Thumbprint  string    `json:"x5t,omitempty"`
	X509CertificateSHA256Thumprint string    `json:"x5t#S256,omitempty"`
}

Header holds metadata about a JWT, including JWS or JWE-specific algorithm and certificate information.

func (*Header) IsValid

func (h *Header) IsValid() error

IsValid checks whether the header contains all required fields and is properly formatted. Returns an error if not.

type Key

type Key struct {
	SymmetricKey []byte            `json:"-"` // required for HMAC, the symmetric key bytes
	PublicKey    crypto.PublicKey  `json:"-"` // required for RSA/EC, the public key
	PrivateKey   crypto.PrivateKey `json:"-"` // optional for RSA/EC, the private key

	KeyType               KeyType        `json:"kty,omitempty"`      // required, the cryptographic algorithm family used with the key
	PublicKeyUse          PublicKeyUse   `json:"use,omitempty"`      // optional, the intended use of the public key
	KeyOperations         []KeyOperation `json:"key_ops,omitempty"`  // optional, list of operations this key is intended to perform
	Algorithm             Algorithm      `json:"alg,omitempty"`      // optional, algorithm intended for use with this key
	KeyID                 string         `json:"kid,omitempty"`      // optional, used to match "kid" value in JWT header
	X509Url               string         `json:"x5u,omitempty"`      // optional, URL of X.509 certificate
	X509CertificateChain  []string       `json:"x5c,omitempty"`      // optional, base64-encoded PKIX certificates (1+)
	X509CertificateSHA1   string         `json:"x5t,omitempty"`      // optional, base64url-encoded SHA-1 fingerprint of X.509
	X509CertificateSHA256 string         `json:"x5t#S256,omitempty"` // optional, base64url-encoded SHA-256 fingerprint of X.509

	Curve EllipticCurve `json:"crv,omitempty"` // required, the elliptic curve for the public key
	X     *bigInt       `json:"x,omitempty"`   // required, the base64url-encoded x-coordinate
	Y     *bigInt       `json:"y,omitempty"`   // required, the base64url-encoded y-coordinate

	N *bigInt `json:"n,omitempty"` // required, the base64urlUint-encoded modulus
	E *bigInt `json:"e,omitempty"` // required, the base64urlUint-encoded exponent

	K string `json:"k,omitempty"` // required, the base64url-encoded key value

	D           *bigInt      `json:"d,omitempty"`   // required for EC/RSA, the base64url-encoded ECC private key or base64urlUint private exponent for RSA
	P           *bigInt      `json:"p,omitempty"`   // required for RSA, the base64urlUint-encoded first prime factor
	Q           *bigInt      `json:"q,omitempty"`   // required for RSA, the base64urlUint-encoded second prime factor
	DP          *bigInt      `json:"dp,omitempty"`  // required for RSA, the base64urlUint-encoded first factor CRT exponent
	DQ          *bigInt      `json:"dq,omitempty"`  // required for RSA, the base64urlUint-encoded second factor CRT exponent
	QI          *bigInt      `json:"qi,omitempty"`  // required for RSA, the base64urlUint-encoded first CRT certificate
	OtherPrimes []OtherPrime `json:"oth,omitempty"` // optional for RSA, the base64urlUint-encoded other primes info
}

Key is a JSON Web Key which holds cryptographic information about the signing/encryption used for a JSON Web Token.

func NewJWKFromECDSAPrivateKey

func NewJWKFromECDSAPrivateKey(key *ecdsa.PrivateKey) (*Key, error)

NewJWKFromECDSAPrivateKey creates a JWK from an ECDSA private key.

func NewJWKFromECDSAPublicKey

func NewJWKFromECDSAPublicKey(key *ecdsa.PublicKey) (*Key, error)

NewJWKFromECDSAPublicKey creates a JWK from an ECDSA public key.

func NewJWKFromRSAPrivateKey

func NewJWKFromRSAPrivateKey(key *rsa.PrivateKey, alg Algorithm) (*Key, error)

NewJWKFromRSAPrivateKey creates a JWK from an RSA private key.

func NewJWKFromRSAPublicKey

func NewJWKFromRSAPublicKey(key *rsa.PublicKey, alg Algorithm) (*Key, error)

NewJWKFromRSAPublicKey creates a JWK from an RSA public key.

func ParseJWK

func ParseJWK(jwk string) (*Key, error)

ParseJWK converts a JSON Web Key to a Key.

func (*Key) HasPrivateKeyInfo

func (key *Key) HasPrivateKeyInfo() error

HasPrivateKeyInfo validates whether or not private key information is included, specific to the algorithm used.

func (*Key) IsPrivateKey

func (key *Key) IsPrivateKey() bool

IsPrivateKey returns true if the key has private key info. Returns false for public and symmetric keys.

func (*Key) IsValid

func (key *Key) IsValid() error

IsValid returns true if this JWK has a valid structure and contents per the requirements of RFC 7417.

func (*Key) PublicJWK

func (key *Key) PublicJWK() *Key

PublicJWK returns the public key given a private key. For public keys, it returns itself.

func (*Key) RetrieveX509Certificate

func (key *Key) RetrieveX509Certificate() (cert []byte, err error)

RetrieveX509Certificate downloads the key's X.509 certificate as specified by the X509Url parameter, if included.

func (*Key) Signer

func (key *Key) Signer() Signer

Signer returns a signing function based off the algorithm and private key.

func (*Key) Thumbprint

func (key *Key) Thumbprint() (string, error)

Thumbprint returns the SHA-256 thumbprint of the key.

func (*Key) Verifier

func (key *Key) Verifier() Verifier

Verifier returns a function for verifying a signature against the public key.

type KeyOperation

type KeyOperation string

KeyOperation specifies the operation(s) for which the key is intended to be used.

const (
	KeyOperationSign        KeyOperation = "sign"
	KeyOperationVerify      KeyOperation = "verify"
	KeyOperationEncrypt     KeyOperation = "encrypt"
	KeyOperationDecrypt     KeyOperation = "decrypt"
	KeyOperationWrapKey     KeyOperation = "wrapKey"
	KeyOperationUnwrapKey   KeyOperation = "unwrapKey"
	KeyOperationDeriveKey   KeyOperation = "deriveKey"
	KeyOperationDeriveBytes KeyOperation = "deriveBytes"
)

Allowed values for KeyOperation as defined by RFC 7517

type KeySet

type KeySet struct {
	Keys []*Key `json:"keys"`
}

KeySet is a JSON Web Key set, used for representing multiple valid JWKs.

func DecodeKeySet

func DecodeKeySet(keySet string) (*KeySet, error)

DecodeKeySet decodes a JSON-encoded key set.

func NewKeySet

func NewKeySet(keys []*Key) *KeySet

NewKeySet creates a new KeySet from the given keys.

func (*KeySet) KeyForAlgorithm

func (ks *KeySet) KeyForAlgorithm(alg Algorithm) (*Key, error)

KeyForAlgorithm returns the key in the set matching the given algorithm.

func (*KeySet) KeyForID

func (ks *KeySet) KeyForID(keyID string) (*Key, error)

KeyForID returns the key in the set matching the given ID.

type KeyType

type KeyType string

KeyType is the cryptographic algorithm family used with the key.

const (
	KeyTypeEllipticCurve KeyType = "EC"  // recommended+
	KeyTypeRSA           KeyType = "RSA" // required
	KeyTypeOctet         KeyType = "oct" // required
)

Valid values for KeyType per RFC 7518

func (KeyType) IsValid

func (typ KeyType) IsValid() bool

IsValid returns true if the key type is supported

type OtherPrime

type OtherPrime struct {
	R *bigInt `json:"r"` // required, the base64urlUint-encoded prime factor
	D *bigInt `json:"d"` // required, the base64urlUint-encoded factor CRT exponent
	T *bigInt `json:"t"` // required, the base64urlUint-encoded factor CRT coefficient
}

OtherPrime is an extra prime for RSA when more than two primes are needed

func (OtherPrime) IsValid

func (oth OtherPrime) IsValid() error

IsValid returns an error if there are problems with the object.

type PublicKeyUse

type PublicKeyUse string

PublicKeyUse defines the intended use of the public key.

const (
	PublicKeyUseSignature  PublicKeyUse = "sig"
	PublicKeyUseEncryption PublicKeyUse = "enc"
)

Allowed values for PublicKeyUse as defined by RFC 7517

func (PublicKeyUse) IsValid

func (use PublicKeyUse) IsValid() error

IsValid checks whether the given use is valid.

type Signer

type Signer func(b []byte) ([]byte, error)

Signer is a function for cryptographically signing tokens.

type Token

type Token struct {
	Header    *Header // The header values
	Claims    *Claims // The claims (registered and custom)
	Signature []byte  // The signature of the token
	// contains filtered or unexported fields
}

Token is a JSON Web Token (JWT)

func Decode

func Decode(token string) (*Token, error)

Decode parses and verifies a token's signature.

func (*Token) Encode

func (t *Token) Encode(key *Key) (string, error)

Encode signs and encodes the token in base64 for transfer on the wire.

func (*Token) IsExpired

func (t *Token) IsExpired() bool

IsExpired returns true if the expiration time has passed.

func (*Token) IssuedBefore

func (t *Token) IssuedBefore(u time.Time) bool

IssuedBefore returns true if the token was issued before the given time.

func (*Token) IssuedBeforeAgo

func (t *Token) IssuedBeforeAgo(d time.Duration) bool

IssuedBeforeAgo returns true if the token was issued before the given duration before now.

func (*Token) Raw

func (t *Token) Raw() (string, error)

Raw returns the raw token string. Must run Encode first on generated tokens.

func (*Token) Valid

func (t *Token) Valid() error

Valid returns nil if the token is valid.

func (*Token) Validate

func (t *Token) Validate(keySet *KeySet) error

Validate verifies the token with the matching key in a key set.

func (*Token) Verify

func (t *Token) Verify(key *Key) error

Verify compares the JWT signature with the expected one based off the provided key.

type Type

type Type string

Type is the type of JWT, used in the

const (
	TypeJWT    Type = "JWT"
	TypeAccess Type = "at+jwt"
	TypeDPoP   Type = "dpop+jwt"
)

Valid JWT types

type Verifier

type Verifier func(msg, sig []byte) error

Verifier is a function for verifying a signature against a public key.

Jump to

Keyboard shortcuts

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