forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/golang-jwt/jwt/v5/parser.go

358 lines
7.3 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
package jwt
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
)
type Parser struct {
2024-02-18 10:42:21 +00:00
// If populated, only these methods will be considered valid.
2024-02-18 10:42:21 +00:00
validMethods []string
// Use JSON Number format in JSON decoder.
2024-02-18 10:42:21 +00:00
useJSONNumber bool
// Skip claims validation during token parsing.
2024-02-18 10:42:21 +00:00
skipClaimsValidation bool
validator *validator
decodeStrict bool
decodePaddingAllowed bool
}
// NewParser creates a new Parser with the specified options
2024-02-18 10:42:21 +00:00
func NewParser(options ...ParserOption) *Parser {
2024-02-18 10:42:21 +00:00
p := &Parser{
2024-02-18 10:42:21 +00:00
validator: &validator{},
}
// Loop through our parsing options and apply them
2024-02-18 10:42:21 +00:00
for _, option := range options {
2024-02-18 10:42:21 +00:00
option(p)
2024-02-18 10:42:21 +00:00
}
return p
2024-02-18 10:42:21 +00:00
}
// Parse parses, validates, verifies the signature and returns the parsed token.
2024-02-18 10:42:21 +00:00
// keyFunc will receive the parsed token and should return the key for validating.
2024-02-18 10:42:21 +00:00
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
2024-02-18 10:42:21 +00:00
return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
2024-02-18 10:42:21 +00:00
}
// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims
2024-02-18 10:42:21 +00:00
// interface. This provides default values which can be overridden and allows a caller to use their own type, rather
2024-02-18 10:42:21 +00:00
// than the default MapClaims implementation of Claims.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims),
2024-02-18 10:42:21 +00:00
// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the
2024-02-18 10:42:21 +00:00
// proper memory for it before passing in the overall claims, otherwise you might run into a panic.
2024-02-18 10:42:21 +00:00
func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
2024-02-18 10:42:21 +00:00
token, parts, err := p.ParseUnverified(tokenString, claims)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return token, err
2024-02-18 10:42:21 +00:00
}
// Verify signing method is in the required set
2024-02-18 10:42:21 +00:00
if p.validMethods != nil {
2024-02-18 10:42:21 +00:00
var signingMethodValid = false
2024-02-18 10:42:21 +00:00
var alg = token.Method.Alg()
2024-02-18 10:42:21 +00:00
for _, m := range p.validMethods {
2024-02-18 10:42:21 +00:00
if m == alg {
2024-02-18 10:42:21 +00:00
signingMethodValid = true
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !signingMethodValid {
2024-02-18 10:42:21 +00:00
// signing method is not in the listed set
2024-02-18 10:42:21 +00:00
return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// Lookup key
2024-02-18 10:42:21 +00:00
var key interface{}
2024-02-18 10:42:21 +00:00
if keyFunc == nil {
2024-02-18 10:42:21 +00:00
// keyFunc was not provided. short circuiting validation
2024-02-18 10:42:21 +00:00
return token, newError("no keyfunc was provided", ErrTokenUnverifiable)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if key, err = keyFunc(token); err != nil {
2024-02-18 10:42:21 +00:00
return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err)
2024-02-18 10:42:21 +00:00
}
// Decode signature
2024-02-18 10:42:21 +00:00
token.Signature, err = p.DecodeSegment(parts[2])
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return token, newError("could not base64 decode signature", ErrTokenMalformed, err)
2024-02-18 10:42:21 +00:00
}
// Perform signature validation
2024-02-18 10:42:21 +00:00
if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
2024-02-18 10:42:21 +00:00
return token, newError("", ErrTokenSignatureInvalid, err)
2024-02-18 10:42:21 +00:00
}
// Validate Claims
2024-02-18 10:42:21 +00:00
if !p.skipClaimsValidation {
2024-02-18 10:42:21 +00:00
// Make sure we have at least a default validator
2024-02-18 10:42:21 +00:00
if p.validator == nil {
2024-02-18 10:42:21 +00:00
p.validator = newValidator()
2024-02-18 10:42:21 +00:00
}
if err := p.validator.Validate(claims); err != nil {
2024-02-18 10:42:21 +00:00
return token, newError("", ErrTokenInvalidClaims, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// No errors so far, token is valid.
2024-02-18 10:42:21 +00:00
token.Valid = true
return token, nil
2024-02-18 10:42:21 +00:00
}
// ParseUnverified parses the token but doesn't validate the signature.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// WARNING: Don't use this method unless you know what you're doing.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It's only ever useful in cases where you know the signature is valid (because it has
2024-02-18 10:42:21 +00:00
// been checked previously in the stack) and you want to extract values from it.
2024-02-18 10:42:21 +00:00
func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) {
2024-02-18 10:42:21 +00:00
parts = strings.Split(tokenString, ".")
2024-02-18 10:42:21 +00:00
if len(parts) != 3 {
2024-02-18 10:42:21 +00:00
return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed)
2024-02-18 10:42:21 +00:00
}
token = &Token{Raw: tokenString}
// parse Header
2024-02-18 10:42:21 +00:00
var headerBytes []byte
2024-02-18 10:42:21 +00:00
if headerBytes, err = p.DecodeSegment(parts[0]); err != nil {
2024-02-18 10:42:21 +00:00
if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
2024-02-18 10:42:21 +00:00
return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
2024-02-18 10:42:21 +00:00
return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err)
2024-02-18 10:42:21 +00:00
}
// parse Claims
2024-02-18 10:42:21 +00:00
var claimBytes []byte
2024-02-18 10:42:21 +00:00
token.Claims = claims
if claimBytes, err = p.DecodeSegment(parts[1]); err != nil {
2024-02-18 10:42:21 +00:00
return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
2024-02-18 10:42:21 +00:00
if p.useJSONNumber {
2024-02-18 10:42:21 +00:00
dec.UseNumber()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// JSON Decode. Special case for map type to avoid weird pointer behavior
2024-02-18 10:42:21 +00:00
if c, ok := token.Claims.(MapClaims); ok {
2024-02-18 10:42:21 +00:00
err = dec.Decode(&c)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
err = dec.Decode(&claims)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Handle decode error
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err)
2024-02-18 10:42:21 +00:00
}
// Lookup signature method
2024-02-18 10:42:21 +00:00
if method, ok := token.Header["alg"].(string); ok {
2024-02-18 10:42:21 +00:00
if token.Method = GetSigningMethod(method); token.Method == nil {
2024-02-18 10:42:21 +00:00
return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable)
2024-02-18 10:42:21 +00:00
}
return token, parts, nil
2024-02-18 10:42:21 +00:00
}
// DecodeSegment decodes a JWT specific base64url encoding. This function will
2024-02-18 10:42:21 +00:00
// take into account whether the [Parser] is configured with additional options,
2024-02-18 10:42:21 +00:00
// such as [WithStrictDecoding] or [WithPaddingAllowed].
2024-02-18 10:42:21 +00:00
func (p *Parser) DecodeSegment(seg string) ([]byte, error) {
2024-02-18 10:42:21 +00:00
encoding := base64.RawURLEncoding
if p.decodePaddingAllowed {
2024-02-18 10:42:21 +00:00
if l := len(seg) % 4; l > 0 {
2024-02-18 10:42:21 +00:00
seg += strings.Repeat("=", 4-l)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
encoding = base64.URLEncoding
2024-02-18 10:42:21 +00:00
}
if p.decodeStrict {
2024-02-18 10:42:21 +00:00
encoding = encoding.Strict()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return encoding.DecodeString(seg)
2024-02-18 10:42:21 +00:00
}
// Parse parses, validates, verifies the signature and returns the parsed token.
2024-02-18 10:42:21 +00:00
// keyFunc will receive the parsed token and should return the cryptographic key
2024-02-18 10:42:21 +00:00
// for verifying the signature. The caller is strongly encouraged to set the
2024-02-18 10:42:21 +00:00
// WithValidMethods option to validate the 'alg' claim in the token matches the
2024-02-18 10:42:21 +00:00
// expected algorithm. For more details about the importance of validating the
2024-02-18 10:42:21 +00:00
// 'alg' claim, see
2024-02-18 10:42:21 +00:00
// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
2024-02-18 10:42:21 +00:00
func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
2024-02-18 10:42:21 +00:00
return NewParser(options...).Parse(tokenString, keyFunc)
2024-02-18 10:42:21 +00:00
}
// ParseWithClaims is a shortcut for NewParser().ParseWithClaims().
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Note: If you provide a custom claim implementation that embeds one of the
2024-02-18 10:42:21 +00:00
// standard claims (such as RegisteredClaims), make sure that a) you either
2024-02-18 10:42:21 +00:00
// embed a non-pointer version of the claims or b) if you are using a pointer,
2024-02-18 10:42:21 +00:00
// allocate the proper memory for it before passing in the overall claims,
2024-02-18 10:42:21 +00:00
// otherwise you might run into a panic.
2024-02-18 10:42:21 +00:00
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
2024-02-18 10:42:21 +00:00
return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
2024-02-18 10:42:21 +00:00
}