2015-10-29 21:45:16 +03:00
|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-03-24 21:13:09 +03:00
|
|
|
"encoding/base64"
|
2015-10-29 21:45:16 +03:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Parser struct {
|
2021-10-13 20:36:33 +03:00
|
|
|
// If populated, only these methods will be considered valid.
|
2023-02-21 16:32:25 +03:00
|
|
|
validMethods []string
|
2021-10-13 20:36:33 +03:00
|
|
|
|
2023-04-02 18:54:36 +03:00
|
|
|
// Use JSON Number format in JSON decoder. This field is disabled when using a custom json encoder.
|
2023-02-21 16:32:25 +03:00
|
|
|
useJSONNumber bool
|
2021-10-13 20:36:33 +03:00
|
|
|
|
|
|
|
// Skip claims validation during token parsing.
|
2023-02-21 16:32:25 +03:00
|
|
|
skipClaimsValidation bool
|
|
|
|
|
2023-11-08 16:21:44 +03:00
|
|
|
validator *Validator
|
2023-03-24 21:13:09 +03:00
|
|
|
|
2023-04-02 18:54:36 +03:00
|
|
|
// This field is disabled when using a custom base64 encoder.
|
2023-03-24 21:13:09 +03:00
|
|
|
decodeStrict bool
|
|
|
|
|
2023-04-02 18:54:36 +03:00
|
|
|
// This field is disabled when using a custom base64 encoder.
|
2023-03-24 21:13:09 +03:00
|
|
|
decodePaddingAllowed bool
|
2023-04-02 18:54:36 +03:00
|
|
|
|
|
|
|
unmarshalFunc JSONUnmarshalFunc
|
|
|
|
base64DecodeFunc Base64DecodeFunc
|
2021-10-13 20:36:33 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewParser creates a new Parser with the specified options
|
|
|
|
func NewParser(options ...ParserOption) *Parser {
|
2023-02-21 16:32:25 +03:00
|
|
|
p := &Parser{
|
2023-11-08 16:21:44 +03:00
|
|
|
validator: &Validator{},
|
2023-02-21 16:32:25 +03:00
|
|
|
}
|
2021-10-13 20:36:33 +03:00
|
|
|
|
2023-02-21 16:32:25 +03:00
|
|
|
// Loop through our parsing options and apply them
|
2021-10-13 20:36:33 +03:00
|
|
|
for _, option := range options {
|
|
|
|
option(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
return p
|
2015-10-29 21:45:16 +03:00
|
|
|
}
|
|
|
|
|
2021-10-15 15:48:31 +03:00
|
|
|
// Parse parses, validates, verifies the signature and returns the parsed token.
|
2015-10-29 21:45:16 +03:00
|
|
|
// keyFunc will receive the parsed token and should return the key for validating.
|
|
|
|
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
2016-04-13 02:25:25 +03:00
|
|
|
return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
|
2015-11-16 22:59:51 +03:00
|
|
|
}
|
|
|
|
|
2022-11-08 17:43:45 +03:00
|
|
|
// 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.
|
2016-04-13 02:25:25 +03:00
|
|
|
func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
|
2016-07-21 19:37:13 +03:00
|
|
|
token, parts, err := p.ParseUnverified(tokenString, claims)
|
2016-04-13 00:32:24 +03:00
|
|
|
if err != nil {
|
2016-07-21 19:37:13 +03:00
|
|
|
return token, err
|
2015-10-29 21:45:16 +03:00
|
|
|
}
|
|
|
|
|
2015-11-03 02:22:08 +03:00
|
|
|
// Verify signing method is in the required set
|
2023-02-21 16:32:25 +03:00
|
|
|
if p.validMethods != nil {
|
2015-11-03 02:22:08 +03:00
|
|
|
var signingMethodValid = false
|
|
|
|
var alg = token.Method.Alg()
|
2023-02-21 16:32:25 +03:00
|
|
|
for _, m := range p.validMethods {
|
2015-11-03 02:22:08 +03:00
|
|
|
if m == alg {
|
|
|
|
signingMethodValid = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !signingMethodValid {
|
|
|
|
// signing method is not in the listed set
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid)
|
2015-11-03 02:22:08 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-13 04:29:27 +03:00
|
|
|
// Decode signature
|
|
|
|
token.Signature, err = p.DecodeSegment(parts[2])
|
|
|
|
if err != nil {
|
|
|
|
return token, newError("could not base64 decode signature", ErrTokenMalformed, err)
|
|
|
|
}
|
|
|
|
text := strings.Join(parts[0:2], ".")
|
|
|
|
|
|
|
|
// Lookup key(s)
|
2015-10-29 21:45:16 +03:00
|
|
|
if keyFunc == nil {
|
|
|
|
// keyFunc was not provided. short circuiting validation
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, newError("no keyfunc was provided", ErrTokenUnverifiable)
|
2015-10-29 21:45:16 +03:00
|
|
|
}
|
|
|
|
|
2023-09-13 04:29:27 +03:00
|
|
|
got, err := keyFunc(token)
|
2023-03-24 21:13:09 +03:00
|
|
|
if err != nil {
|
2023-09-13 04:29:27 +03:00
|
|
|
return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err)
|
2023-03-24 21:13:09 +03:00
|
|
|
}
|
|
|
|
|
2023-09-13 04:29:27 +03:00
|
|
|
switch have := got.(type) {
|
|
|
|
case VerificationKeySet:
|
|
|
|
if len(have.Keys) == 0 {
|
|
|
|
return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable)
|
|
|
|
}
|
|
|
|
// Iterate through keys and verify signature, skipping the rest when a match is found.
|
|
|
|
// Return the last error if no match is found.
|
|
|
|
for _, key := range have.Keys {
|
|
|
|
if err = token.Method.Verify(text, token.Signature, key); err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
err = token.Method.Verify(text, token.Signature, have)
|
|
|
|
}
|
|
|
|
if err != nil {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, newError("", ErrTokenSignatureInvalid, err)
|
|
|
|
}
|
2015-11-16 22:59:51 +03:00
|
|
|
|
|
|
|
// Validate Claims
|
2023-02-21 16:32:25 +03:00
|
|
|
if !p.skipClaimsValidation {
|
|
|
|
// Make sure we have at least a default validator
|
|
|
|
if p.validator == nil {
|
2023-11-08 16:21:44 +03:00
|
|
|
p.validator = NewValidator()
|
2015-10-29 21:45:16 +03:00
|
|
|
}
|
|
|
|
|
2023-02-21 16:32:25 +03:00
|
|
|
if err := p.validator.Validate(claims); err != nil {
|
|
|
|
return token, newError("", ErrTokenInvalidClaims, err)
|
|
|
|
}
|
2015-10-29 21:45:16 +03:00
|
|
|
}
|
|
|
|
|
2023-02-21 16:32:25 +03:00
|
|
|
// No errors so far, token is valid.
|
|
|
|
token.Valid = true
|
2015-10-29 21:45:16 +03:00
|
|
|
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, nil
|
2015-10-29 21:45:16 +03:00
|
|
|
}
|
2016-07-21 19:37:13 +03:00
|
|
|
|
2021-08-03 16:51:01 +03:00
|
|
|
// ParseUnverified parses the token but doesn't validate the signature.
|
2016-07-21 19:37:13 +03:00
|
|
|
//
|
2021-08-03 16:51:01 +03:00
|
|
|
// WARNING: Don't use this method unless you know what you're doing.
|
|
|
|
//
|
2023-08-22 21:26:47 +03:00
|
|
|
// It's only ever useful in cases where you know the signature is valid (since it has already
|
|
|
|
// been or will be checked elsewhere in the stack) and you want to extract values from it.
|
2016-07-21 19:37:13 +03:00
|
|
|
func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) {
|
|
|
|
parts = strings.Split(tokenString, ".")
|
|
|
|
if len(parts) != 3 {
|
2023-02-21 16:32:25 +03:00
|
|
|
return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
token = &Token{Raw: tokenString}
|
|
|
|
|
|
|
|
// parse Header
|
|
|
|
var headerBytes []byte
|
2023-03-24 21:13:09 +03:00
|
|
|
if headerBytes, err = p.DecodeSegment(parts[0]); err != nil {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
2023-04-02 18:54:36 +03:00
|
|
|
|
|
|
|
// Choose our JSON decoder. If no custom function is supplied, we use the standard library.
|
|
|
|
var unmarshal JSONUnmarshalFunc
|
|
|
|
if p.unmarshalFunc != nil {
|
|
|
|
unmarshal = p.unmarshalFunc
|
|
|
|
} else {
|
|
|
|
unmarshal = json.Unmarshal
|
|
|
|
}
|
|
|
|
|
2023-09-13 17:49:08 +03:00
|
|
|
// JSON Unmarshal the header
|
2023-04-02 18:54:36 +03:00
|
|
|
err = unmarshal(headerBytes, &token.Header)
|
|
|
|
if err != nil {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// parse Claims
|
|
|
|
token.Claims = claims
|
|
|
|
|
2023-08-15 18:06:50 +03:00
|
|
|
claimBytes, err := p.DecodeSegment(parts[1])
|
|
|
|
if err != nil {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
2023-08-15 18:06:50 +03:00
|
|
|
|
2023-09-13 17:49:08 +03:00
|
|
|
// If `useJSONNumber` is enabled, then we must use *json.Decoder to decode
|
2023-08-15 18:06:50 +03:00
|
|
|
// the claims. However, this comes with a performance penalty so only use
|
2023-09-13 17:49:08 +03:00
|
|
|
// it if we must and, otherwise, simple use our existing unmarshal function.
|
|
|
|
if p.useJSONNumber {
|
|
|
|
unmarshal = func(data []byte, v any) error {
|
|
|
|
decoder := json.NewDecoder(bytes.NewBuffer(claimBytes))
|
|
|
|
decoder.UseNumber()
|
|
|
|
return decoder.Decode(v)
|
2023-08-15 18:06:50 +03:00
|
|
|
}
|
2023-09-13 17:49:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// JSON Unmarshal the claims. Special case for map type to avoid weird
|
|
|
|
// pointer behavior.
|
|
|
|
if c, ok := token.Claims.(MapClaims); ok {
|
|
|
|
err = unmarshal(claimBytes, &c)
|
2016-07-21 19:37:13 +03:00
|
|
|
} else {
|
2023-09-13 17:49:08 +03:00
|
|
|
err = unmarshal(claimBytes, &claims)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
|
|
|
if err != nil {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Lookup signature method
|
|
|
|
if method, ok := token.Header["alg"].(string); ok {
|
|
|
|
if token.Method = GetSigningMethod(method); token.Method == nil {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
|
|
|
} else {
|
2023-02-21 16:32:25 +03:00
|
|
|
return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable)
|
2016-07-21 19:37:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return token, parts, nil
|
|
|
|
}
|
2023-03-24 21:13:09 +03:00
|
|
|
|
|
|
|
// DecodeSegment decodes a JWT specific base64url encoding. This function will
|
|
|
|
// take into account whether the [Parser] is configured with additional options,
|
|
|
|
// such as [WithStrictDecoding] or [WithPaddingAllowed].
|
|
|
|
func (p *Parser) DecodeSegment(seg string) ([]byte, error) {
|
2023-04-02 18:54:36 +03:00
|
|
|
if p.base64DecodeFunc != nil {
|
|
|
|
return p.base64DecodeFunc(seg)
|
|
|
|
}
|
|
|
|
|
2023-03-24 21:13:09 +03:00
|
|
|
encoding := base64.RawURLEncoding
|
|
|
|
|
|
|
|
if p.decodePaddingAllowed {
|
|
|
|
if l := len(seg) % 4; l > 0 {
|
|
|
|
seg += strings.Repeat("=", 4-l)
|
|
|
|
}
|
|
|
|
encoding = base64.URLEncoding
|
|
|
|
}
|
|
|
|
|
|
|
|
if p.decodeStrict {
|
|
|
|
encoding = encoding.Strict()
|
|
|
|
}
|
|
|
|
return encoding.DecodeString(seg)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
|
|
|
|
return NewParser(options...).Parse(tokenString, keyFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
|
|
|
|
return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
|
|
|
|
}
|