package jwtimport ()consttokenDelimiter = "."typeParserstruct {// If populated, only these methods will be considered valid.validMethods []string// Use JSON Number format in JSON decoder.useJSONNumberbool// Skip claims validation during token parsing.skipClaimsValidationboolvalidator *ValidatordecodeStrictbooldecodePaddingAllowedbool}// NewParser creates a new Parser with the specified optionsfunc ( ...ParserOption) *Parser { := &Parser{validator: &Validator{}, }// Loop through our parsing options and apply themfor , := range { () }return}// 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) ( string, Keyfunc) (*Token, error) {return .ParseWithClaims(, MapClaims{}, )}// 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.func ( *Parser) ( string, Claims, Keyfunc) (*Token, error) { , , := .ParseUnverified(, )if != nil {return , }// Verify signing method is in the required setif .validMethods != nil {var = falsevar = .Method.Alg()for , := range .validMethods {if == { = truebreak } }if ! {// signing method is not in the listed setreturn , newError(fmt.Sprintf("signing method %v is invalid", ), ErrTokenSignatureInvalid) } }// Decode signature .Signature, = .DecodeSegment([2])if != nil {return , newError("could not base64 decode signature", ErrTokenMalformed, ) } := strings.Join([0:2], ".")// Lookup key(s)if == nil {// keyFunc was not provided. short circuiting validationreturn , newError("no keyfunc was provided", ErrTokenUnverifiable) } , := ()if != nil {return , newError("error while executing keyfunc", ErrTokenUnverifiable, ) }switch have := .(type) {caseVerificationKeySet:iflen(.Keys) == 0 {return , 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 , := range .Keys {if = .Method.Verify(, .Signature, ); == nil {break } }default: = .Method.Verify(, .Signature, ) }if != nil {return , newError("", ErrTokenSignatureInvalid, ) }// Validate Claimsif !.skipClaimsValidation {// Make sure we have at least a default validatorif .validator == nil { .validator = NewValidator() }if := .validator.Validate(); != nil {return , newError("", ErrTokenInvalidClaims, ) } }// No errors so far, token is valid. .Valid = truereturn , nil}// 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 (since it has already// been or will be checked elsewhere in the stack) and you want to extract values from it.func ( *Parser) ( string, Claims) ( *Token, []string, error) {varbool , = splitToken()if ! {returnnil, nil, newError("token contains an invalid number of segments", ErrTokenMalformed) } = &Token{Raw: }// parse Headervar []byteif , = .DecodeSegment([0]); != nil {return , , newError("could not base64 decode header", ErrTokenMalformed, ) }if = json.Unmarshal(, &.Header); != nil {return , , newError("could not JSON decode header", ErrTokenMalformed, ) }// parse Claims .Claims = , := .DecodeSegment([1])if != nil {return , , newError("could not base64 decode claim", ErrTokenMalformed, ) }// If `useJSONNumber` is enabled then we must use *json.Decoder to decode // the claims. However, this comes with a performance penalty so only use // it if we must and, otherwise, simple use json.Unmarshal.if !.useJSONNumber {// JSON Unmarshal. Special case for map type to avoid weird pointer behavior.if , := .Claims.(MapClaims); { = json.Unmarshal(, &) } else { = json.Unmarshal(, &) } } else { := json.NewDecoder(bytes.NewBuffer()) .UseNumber()// JSON Decode. Special case for map type to avoid weird pointer behavior.if , := .Claims.(MapClaims); { = .Decode(&) } else { = .Decode(&) } }if != nil {return , , newError("could not JSON decode claim", ErrTokenMalformed, ) }// Lookup signature methodif , := .Header["alg"].(string); {if .Method = GetSigningMethod(); .Method == nil {return , , newError("signing method (alg) is unavailable", ErrTokenUnverifiable) } } else {return , , newError("signing method (alg) is unspecified", ErrTokenUnverifiable) }return , , nil}// splitToken splits a token string into three parts: header, claims, and signature. It will only// return true if the token contains exactly two delimiters and three parts. In all other cases, it// will return nil parts and false.func ( string) ([]string, bool) { := make([]string, 3) , , := strings.Cut(, tokenDelimiter)if ! {returnnil, false } [0] = , , := strings.Cut(, tokenDelimiter)if ! {returnnil, false } [1] = // One more cut to ensure the signature is the last part of the token and there are no more // delimiters. This avoids an issue where malicious input could contain additional delimiters // causing unecessary overhead parsing tokens. , , := strings.Cut(, tokenDelimiter)if {returnnil, false } [2] = return , true}// 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 ( *Parser) ( string) ([]byte, error) { := base64.RawURLEncodingif .decodePaddingAllowed {if := len() % 4; > 0 { += strings.Repeat("=", 4-) } = base64.URLEncoding }if .decodeStrict { = .Strict() }return .DecodeString()}// 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 ( string, Keyfunc, ...ParserOption) (*Token, error) {returnNewParser(...).Parse(, )}// 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 ( string, Claims, Keyfunc, ...ParserOption) (*Token, error) {returnNewParser(...).ParseWithClaims(, , )}
The pages are generated with Goldsv0.7.6. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.