jwt

package
v0.0.0-...-0116310 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2025 License: BSD-3-Clause, MIT Imports: 22 Imported by: 1

Documentation

Index

Constants

View Source
const (
	ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
	ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
	ValidationErrorSignatureInvalid                    // Signature validation failed

	// Standard Claim validation errors
	ValidationErrorAudience      // AUD validation failed
	ValidationErrorExpired       // EXP validation failed
	ValidationErrorIssuedAt      // IAT validation failed
	ValidationErrorIssuer        // ISS validation failed
	ValidationErrorNotValidYet   // NBF validation failed
	ValidationErrorId            // JTI validation failed
	ValidationErrorClaimsInvalid // Generic claims validation error
)

The errors that might occur when parsing and validating a token

View Source
const (
	Ed448Context string = ""
)
View Source
const (
	Edx448Context string = ""
)

Variables

View Source
var (
	ErrNotEdPrivateKey error = errors.New("key is not a valid Ed25519 private key")
	ErrNotEdPublicKey  error = errors.New("key is not a valid Ed25519 public key")
)
View Source
var (
	ErrNotEdzPrivateKey error = errors.New("key is not a valid Ed448 private key")
	ErrNotEdzPublicKey  error = errors.New("key is not a valid Ed448 public key")
)
View Source
var (
	ErrNotEdxPrivateKey error = errors.New("key is not a valid Edx25519 private key")
	ErrNotEdxPublicKey  error = errors.New("key is not a valid Edx25519 public key")
)
View Source
var (
	ErrNotEdzxPrivateKey error = errors.New("key is not a valid Edx448 private key")
	ErrNotEdzxPublicKey  error = errors.New("key is not a valid Edx448 public key")
)
View Source
var (
	ErrInvalidKey      = errors.New("key is invalid")
	ErrInvalidKeyType  = errors.New("key is of invalid type")
	ErrHashUnavailable = errors.New("the requested hash function is unavailable")

	ErrTokenMalformed        = errors.New("token is malformed")
	ErrTokenUnverifiable     = errors.New("token is unverifiable")
	ErrTokenSignatureInvalid = errors.New("token signature is invalid")

	ErrTokenInvalidAudience  = errors.New("token has invalid audience")
	ErrTokenExpired          = errors.New("token is expired")
	ErrTokenUsedBeforeIssued = errors.New("token used before issued")
	ErrTokenInvalidIssuer    = errors.New("token has invalid issuer")
	ErrTokenNotValidYet      = errors.New("token is not valid yet")
	ErrTokenInvalidId        = errors.New("token has invalid id")
	ErrTokenInvalidClaims    = errors.New("token has invalid claims")

	ErrKeyMustBeEncodedPem = errors.New("invalid key: Key must be a PEM encoded")
)

Error constants

View Source
var DecodePaddingAllowed bool

DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. To use the non-recommended decoding, set this boolean to `true` prior to using this package.

View Source
var DecodeStrict bool

DecodeStrict will switch the codec used for decoding JWTs into strict mode. In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5. Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. To use strict decoding, set this boolean to `true` prior to using this package.

View Source
var (
	ErrEd25519Verification error = errors.New("ed25519: verification error")
)
View Source
var (
	ErrEd448Verification error = errors.New("ed448: verification error")
)
View Source
var (
	ErrEdx25519Verification error = errors.New("edx25519: verification error")
)
View Source
var (
	ErrEdx448Verification error = errors.New("edx448: verification error")
)
View Source
var MarshalSingleStringAsArray = true

MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially its MarshalJSON function.

If it is set to true (the default), it will always serialize the type as an array of strings, even if it just contains one element, defaulting to the behaviour of the underlying []string. If it is set to false, it will serialize to a single string, if it contains one element. Otherwise, it will serialize to an array of strings.

View Source
var TimeFunc = time.Now

TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.

View Source
var TimePrecision = time.Second

TimePrecision sets the precision of times and dates within this library. This has an influence on the precision of times when comparing expiry or other related time fields. Furthermore, it is also the precision of times when serializing.

For backwards compatibility the default precision is set to seconds, so that no fractional timestamps are generated.

Functions

func DecodeSegment

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

DecodeSegment decodes a JWT specific base64url encoding with padding stripped unixman: added panic handler ; fix: if padding is invalid (L=3) exit and notice err

func EncodeSegment

func EncodeSegment(seg []byte) string

EncodeSegment encodes a JWT specific base64url encoding with padding stripped

func GenerateEdPrivateAndPublicKeys

func GenerateEdPrivateAndPublicKeys(secret []byte) (ed25519.PrivateKey, []byte, error)

func GenerateEdPrivateKey

func GenerateEdPrivateKey(secret []byte) (ed25519.PrivateKey, error)

func GenerateEdxPrivateAndPublicKeys

func GenerateEdxPrivateAndPublicKeys(secret []byte) (edx25519.PrivateKey, []byte, error)

func GenerateEdxPrivateKey

func GenerateEdxPrivateKey(secret []byte) (edx25519.PrivateKey, error)

func GenerateEdzPrivateAndPublicKeys

func GenerateEdzPrivateAndPublicKeys(secret []byte) (ed448.PrivateKey, []byte, error)

func GenerateEdzPrivateKey

func GenerateEdzPrivateKey(secret []byte) (ed448.PrivateKey, error)

func GenerateEdzxPrivateAndPublicKeys

func GenerateEdzxPrivateAndPublicKeys(secret []byte) (edx448.PrivateKey, []byte, error)

func GenerateEdzxPrivateKey

func GenerateEdzxPrivateKey(secret []byte) (edx448.PrivateKey, error)

func GetAlgorithms

func GetAlgorithms() (algs []string)

GetAlgorithms returns a list of registered "alg" names

func GetEdPublicKeyFromBytes

func GetEdPublicKeyFromBytes(pKey []byte) ed25519.PublicKey

func GetEdPublicKeyFromPrivateKeyToBytes

func GetEdPublicKeyFromPrivateKeyToBytes(privateKey ed25519.PrivateKey) []byte

func GetEdxPublicKeyFromBytes

func GetEdxPublicKeyFromBytes(pKey []byte) edx25519.PublicKey

func GetEdxPublicKeyFromPrivateKeyToBytes

func GetEdxPublicKeyFromPrivateKeyToBytes(privateKey edx25519.PrivateKey) []byte

func GetEdzPublicKeyFromBytes

func GetEdzPublicKeyFromBytes(pKey []byte) ed448.PublicKey

func GetEdzPublicKeyFromPrivateKeyToBytes

func GetEdzPublicKeyFromPrivateKeyToBytes(privateKey ed448.PrivateKey) []byte

func GetEdzxPublicKeyFromBytes

func GetEdzxPublicKeyFromBytes(pKey []byte) edx448.PublicKey

func GetEdzxPublicKeyFromPrivateKeyToBytes

func GetEdzxPublicKeyFromPrivateKeyToBytes(privateKey edx448.PrivateKey) []byte

func RegisterSigningMethod

func RegisterSigningMethod(alg string, f func() SigningMethod)

RegisterSigningMethod registers the "alg" name and a factory function for signing method. This is typically done during init() in the method's implementation

Types

type ClaimStrings

type ClaimStrings []string

ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. This type is necessary, since the "aud" claim can either be a single string or an array.

func (ClaimStrings) MarshalJSON

func (s ClaimStrings) MarshalJSON() (b []byte, err error)

func (*ClaimStrings) UnmarshalJSON

func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error)

type Claims

type Claims interface {
	Valid() error
}

Claims must just have a Valid method that determines if the token is invalid for any supported reason

type Keyfunc

type Keyfunc func(*Token) (interface{}, error)

Keyfunc will be used by the Parse methods as 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

type MapClaims map[string]interface{}

MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. This is the default claims type if you don't supply one

func (MapClaims) Valid

func (m MapClaims) Valid() error

Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (MapClaims) VerifyAudience

func (m MapClaims) VerifyAudience(cmp string, req bool) bool

VerifyAudience Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyExpiresAt

func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool

VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). If req is false, it will return true, if exp is unset.

func (MapClaims) VerifyIssuedAt

func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool

VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset.

func (MapClaims) VerifyIssuer

func (m MapClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (MapClaims) VerifyNotBefore

func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool

VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset.

type NumericDate

type NumericDate struct {
	time.Time
}

NumericDate represents a JSON numeric date value, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-2.

func NewNumericDate

func NewNumericDate(t time.Time) *NumericDate

NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. It will truncate the timestamp according to the precision specified in TimePrecision.

func (NumericDate) MarshalJSON

func (date NumericDate) MarshalJSON() (b []byte, err error)

MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch represented in NumericDate to a byte array, using the precision specified in TimePrecision.

func (*NumericDate) UnmarshalJSON

func (date *NumericDate) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch with either integer or non-integer seconds.

type Parser

type Parser struct {
	// If populated, only these methods will be considered valid.
	ValidMethods []string

	// Use JSON Number format in JSON decoder.
	UseJSONNumber bool

	// Skip claims validation during token parsing.
	SkipClaimsValidation bool
}

func NewParser

func NewParser(options ...ParserOption) *Parser

NewParser creates a new Parser with the specified options

func (*Parser) Parse

func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

Parse parses, validates, verifies the signature and returns the parsed token. keyFunc will receive the parsed token and should return the key for validating.

func (*Parser) ParseUnverified

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

ParseUnverified parses the token but doesn't validate the signature.

WARNING: Don't use this method unless you know what you're doing.

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.

func (*Parser) ParseWithClaims

func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)

ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims interface. This provides default values which can be overridden and allows a caller to use their own type, rather than the default MapClaims implementation of Claims.

Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the proper memory for it before passing in the overall claims, otherwise you might run into a panic.

type ParserOption

type ParserOption func(*Parser)

ParserOption is used to implement functional-style options that modify the behavior of the parser. To add new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that takes a *Parser type as input and manipulates its configuration accordingly.

func WithJSONNumber

func WithJSONNumber() ParserOption

WithJSONNumber is an option to configure the underlying JSON parser with UseNumber

func WithValidMethods

func WithValidMethods(methods []string) ParserOption

WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid. It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/.

func WithoutClaimsValidation

func WithoutClaimsValidation() ParserOption

WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know what you are doing.

type RegisteredClaims

type RegisteredClaims struct {
	// the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1
	Issuer string `json:"iss,omitempty"`

	// the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2
	Subject string `json:"sub,omitempty"`

	// the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3
	Audience ClaimStrings `json:"aud,omitempty"`

	// the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4
	ExpiresAt *NumericDate `json:"exp,omitempty"`

	// the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5
	NotBefore *NumericDate `json:"nbf,omitempty"`

	// the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6
	IssuedAt *NumericDate `json:"iat,omitempty"`

	// the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7
	ID string `json:"jti,omitempty"`
}

RegisteredClaims are a structured version of the JWT Claims Set, restricted to Registered Claim Names, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-4.1

This type can be used on its own, but then additional private and public claims embedded in the JWT will not be parsed. The typical usecase therefore is to embedded this in a user-defined claim type.

See examples for how to use this with your own claim types.

func (RegisteredClaims) Valid

func (c RegisteredClaims) Valid() error

Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*RegisteredClaims) VerifyAudience

func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool

VerifyAudience compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*RegisteredClaims) VerifyExpiresAt

func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool

VerifyExpiresAt compares the exp claim against cmp (cmp < exp). If req is false, it will return true, if exp is unset.

func (*RegisteredClaims) VerifyIssuedAt

func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool

VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset.

func (*RegisteredClaims) VerifyIssuer

func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*RegisteredClaims) VerifyNotBefore

func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool

VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset.

type SigningMethod

type SigningMethod interface {
	Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid
	Sign(signingString string, key interface{}) (string, error)    // Returns encoded signature or error
	Alg() string                                                   // returns the alg identifier for this method (example: 'HS256')
}

SigningMethod can be used add new methods for signing or verifying tokens.

func GetSigningMethod

func GetSigningMethod(alg string) (method SigningMethod)

GetSigningMethod retrieves a signing method from an "alg" string

type SigningMethodEd25519

type SigningMethodEd25519 struct{}

SigningMethodEd25519 implements the EdDSA family. Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification

var (
	SigningMethodEdDSA *SigningMethodEd25519
)

Specific instance for EdDSA

func (*SigningMethodEd25519) Alg

func (m *SigningMethodEd25519) Alg() string

func (*SigningMethodEd25519) Sign

func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an ed25519.PrivateKey

func (*SigningMethodEd25519) Verify

func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an ed25519.PublicKey

type SigningMethodEd448

type SigningMethodEd448 struct{}

SigningMethodEd448 implements the EdDSA family. Expects ed448.PrivateKey for signing and ed448.PublicKey for verification

var (
	SigningMethodEdzDSA *SigningMethodEd448
)

Specific instance for EdDSA

func (*SigningMethodEd448) Alg

func (m *SigningMethodEd448) Alg() string

func (*SigningMethodEd448) Sign

func (m *SigningMethodEd448) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an ed448.PrivateKey

func (*SigningMethodEd448) Verify

func (m *SigningMethodEd448) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an ed448.PublicKey

type SigningMethodEdx25519

type SigningMethodEdx25519 struct{}

SigningMethodEdx25519 implements the EdxDSA family. Expects edx25519.PrivateKey for signing and edx25519.PublicKey for verification

var (
	SigningMethodEdxDSA *SigningMethodEdx25519
)

Specific instance for EdxDSA

func (*SigningMethodEdx25519) Alg

func (m *SigningMethodEdx25519) Alg() string

func (*SigningMethodEdx25519) Sign

func (m *SigningMethodEdx25519) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an edx25519.PrivateKey

func (*SigningMethodEdx25519) Verify

func (m *SigningMethodEdx25519) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an edx25519.PublicKey

type SigningMethodEdx448

type SigningMethodEdx448 struct{}

SigningMethodEdx448 implements the EdDSA family. Expects edx448.PrivateKey for signing and edx448.PublicKey for verification

var (
	SigningMethodEdzxDSA *SigningMethodEdx448
)

Specific instance for EdDSA

func (*SigningMethodEdx448) Alg

func (m *SigningMethodEdx448) Alg() string

func (*SigningMethodEdx448) Sign

func (m *SigningMethodEdx448) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. For this signing method, key must be an edx448.PrivateKey

func (*SigningMethodEdx448) Verify

func (m *SigningMethodEdx448) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. For this verify method, key must be an edx448.PublicKey

type SigningMethodHMAC

type SigningMethodHMAC struct {
	Name string
	Hash crypto.Hash
}

SigningMethodHMAC implements the HMAC-SHA family of signing methods. Expects key type of []byte for both signing and validation

var (
	SigningMethodHS224 *SigningMethodHMAC
	//	SigningMethodHS256   *SigningMethodHMAC // unsafe to use for signature, it may be vulnerable to length attack
	SigningMethodHS384 *SigningMethodHMAC

	SigningMethodH3S224 *SigningMethodHMAC
	SigningMethodH3S256 *SigningMethodHMAC
	SigningMethodH3S384 *SigningMethodHMAC
	SigningMethodH3S512 *SigningMethodHMAC

	ErrSignatureInvalid = errors.New("signature is invalid")
)

Specific instances for HS256 and company

func (*SigningMethodHMAC) Alg

func (m *SigningMethodHMAC) Alg() string

func (*SigningMethodHMAC) Sign

func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error)

Sign implements token signing for the SigningMethod. Key must be []byte

func (*SigningMethodHMAC) Verify

func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error

Verify implements token verification for the SigningMethod. Returns nil if the signature is valid.

type StandardClaims

type StandardClaims struct {
	Audience  string `json:"aud,omitempty"`
	ExpiresAt int64  `json:"exp,omitempty"`
	Id        string `json:"jti,omitempty"`
	IssuedAt  int64  `json:"iat,omitempty"`
	Issuer    string `json:"iss,omitempty"`
	NotBefore int64  `json:"nbf,omitempty"`
	Subject   string `json:"sub,omitempty"`
}

StandardClaims are a structured version of the JWT Claims Set, as referenced at https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the specification exactly, since they were based on an earlier draft of the specification and not updated. The main difference is that they only support integer-based date fields and singular audiences. This might lead to incompatibilities with other JWT implementations. The use of this is discouraged, instead the newer RegisteredClaims struct should be used.

Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct.

func (StandardClaims) Valid

func (c StandardClaims) Valid() error

Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*StandardClaims) VerifyAudience

func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool

VerifyAudience compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyExpiresAt

func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool

VerifyExpiresAt compares the exp claim against cmp (cmp < exp). If req is false, it will return true, if exp is unset.

func (*StandardClaims) VerifyIssuedAt

func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool

VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). If req is false, it will return true, if iat is unset.

func (*StandardClaims) VerifyIssuer

func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset

func (*StandardClaims) VerifyNotBefore

func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool

VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). If req is false, it will return true, if nbf is unset.

type Token

type Token struct {
	Raw       string                 // The raw token.  Populated when you Parse a token
	Method    SigningMethod          // The signing method used or to be used
	Header    map[string]interface{} // The first segment of the token
	Claims    Claims                 // 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 represents a JWT Token. Different fields will be used depending on whether you're creating or parsing/verifying a token.

func New

func New(method SigningMethod) *Token

New creates a new Token with the specified signing method and an empty map of claims.

func NewWithClaims

func NewWithClaims(method SigningMethod, claims Claims) *Token

NewWithClaims creates a new Token with the specified signing method and claims.

func Parse

func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error)

Parse parses, validates, verifies the signature and returns the parsed token. keyFunc will receive the parsed token and should return the cryptographic key for verifying the signature. The caller is strongly encouraged to set the WithValidMethods option to validate the 'alg' claim in the token matches the expected algorithm. For more details about the importance of validating the 'alg' claim, see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/

func ParseWithClaims

func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error)

ParseWithClaims is a shortcut for NewParser().ParseWithClaims().

Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the proper memory for it before passing in the overall claims, otherwise you might run into a panic.

func (*Token) SignedString

func (t *Token) SignedString(key interface{}) (string, error)

SignedString creates and returns a complete, signed JWT. The token is signed using the SigningMethod specified in the token.

func (*Token) SigningString

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

SigningString generates the signing string. This is the most expensive part of the whole deal. Unless you need this for something special, just go straight for the SignedString.

type ValidationError

type ValidationError struct {
	Inner  error  // stores the error returned by external dependencies, i.e.: KeyFunc
	Errors uint32 // bitfield.  see ValidationError... constants
	// contains filtered or unexported fields
}

ValidationError represents an error from Parse if token is not valid

func NewValidationError

func NewValidationError(errorText string, errorFlags uint32) *ValidationError

NewValidationError is a helper for constructing a ValidationError with a string error message

func (ValidationError) Error

func (e ValidationError) Error() string

Error is the implementation of the err interface.

func (*ValidationError) Is

func (e *ValidationError) Is(err error) bool

Is checks if this ValidationError is of the supplied error. We are first checking for the exact error message by comparing the inner error message. If that fails, we compare using the error flags. This way we can use custom error messages (mainly for backwards compatability) and still leverage errors.Is using the global error variables.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap gives errors.Is and errors.As access to the inner error.

Jump to

Keyboard shortcuts

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