Debian Codegraph @

vendor/github.com/dgrijalva/jwt-go/parser.go

raw
1 package jwt
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "strings"
8 )
9
10 type Parser struct {
11 ValidMethods []string // If populated, only these methods will be considered valid
12 UseJSONNumber bool // Use JSON Number format in JSON decoder
13 }
14
15 // Parse, validate, and return a token.
16 // keyFunc will receive the parsed token and should return the key for validating.
17 // If everything is kosher, err will be nil
18 func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
19 return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
20 }
21
22 func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
23 parts := strings.Split(tokenString, ".")
24 if len(parts) != 3 {
25 return nil, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
26 }
27
28 var err error
29 token := &Token{Raw: tokenString}
30
31 // parse Header
32 var headerBytes []byte
33 if headerBytes, err = DecodeSegment(parts[0]); err != nil {
34 if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
35 return token, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
36 }
37 return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
38 }
39 if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
40 return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
41 }
42
43 // parse Claims
44 var claimBytes []byte
45 token.Claims = claims
46
47 if claimBytes, err = DecodeSegment(parts[1]); err != nil {
48 return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
49 }
50 dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
51 if p.UseJSONNumber {
52 dec.UseNumber()
53 }
54 // JSON Decode. Special case for map type to avoid weird pointer behavior
55 if c, ok := token.Claims.(MapClaims); ok {
56 err = dec.Decode(&c)
57 } else {
58 err = dec.Decode(&claims)
59 }
60 // Handle decode error
61 if err != nil {
62 return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
63 }
64
65 // Lookup signature method
66 if method, ok := token.Header["alg"].(string); ok {
67 if token.Method = GetSigningMethod(method); token.Method == nil {
68 return token, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
69 }
70 } else {
71 return token, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
72 }
73
74 // Verify signing method is in the required set
75 if p.ValidMethods != nil {
76 var signingMethodValid = false
77 var alg = token.Method.Alg()
78 for _, m := range p.ValidMethods {
79 if m == alg {
80 signingMethodValid = true
81 break
82 }
83 }
84 if !signingMethodValid {
85 // signing method is not in the listed set
86 return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid)
87 }
88 }
89
90 // Lookup key
91 var key interface{}
92 if keyFunc == nil {
93 // keyFunc was not provided. short circuiting validation
94 return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable)
95 }
96 if key, err = keyFunc(token); err != nil {
97 // keyFunc returned an error
98 return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
99 }
100
101 vErr := &ValidationError{}
102
103 // Validate Claims
104 if err := token.Claims.Valid(); err != nil {
105
106 // If the Claims Valid returned an error, check if it is a validation error,
107 // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
108 if e, ok := err.(*ValidationError); !ok {
109 vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
110 } else {
111 vErr = e
112 }
113 }
114
115 // Perform validation
116 token.Signature = parts[2]
117 if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
118 vErr.Inner = err
119 vErr.Errors |= ValidationErrorSignatureInvalid
120 }
121
122 if vErr.valid() {
123 token.Valid = true
124 return token, nil
125 }
126
127 return token, vErr
128 }