parser.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package jwt
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. )
  8. type Parser struct {
  9. // If populated, only these methods will be considered valid.
  10. //
  11. // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
  12. ValidMethods []string
  13. // Use JSON Number format in JSON decoder.
  14. //
  15. // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
  16. UseJSONNumber bool
  17. // Skip claims validation during token parsing.
  18. //
  19. // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
  20. SkipClaimsValidation bool
  21. }
  22. // NewParser creates a new Parser with the specified options
  23. func NewParser(options ...ParserOption) *Parser {
  24. p := &Parser{}
  25. // loop through our parsing options and apply them
  26. for _, option := range options {
  27. option(p)
  28. }
  29. return p
  30. }
  31. // Parse parses, validates, verifies the signature and returns the parsed token.
  32. // keyFunc will receive the parsed token and should return the key for validating.
  33. func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
  34. return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
  35. }
  36. // ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims
  37. // interface. This provides default values which can be overridden and allows a caller to use their own type, rather
  38. // than the default MapClaims implementation of Claims.
  39. //
  40. // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims),
  41. // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the
  42. // proper memory for it before passing in the overall claims, otherwise you might run into a panic.
  43. func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
  44. token, parts, err := p.ParseUnverified(tokenString, claims)
  45. if err != nil {
  46. return token, err
  47. }
  48. // Verify signing method is in the required set
  49. if p.ValidMethods != nil {
  50. var signingMethodValid = false
  51. var alg = token.Method.Alg()
  52. for _, m := range p.ValidMethods {
  53. if m == alg {
  54. signingMethodValid = true
  55. break
  56. }
  57. }
  58. if !signingMethodValid {
  59. // signing method is not in the listed set
  60. return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid)
  61. }
  62. }
  63. // Lookup key
  64. var key interface{}
  65. if keyFunc == nil {
  66. // keyFunc was not provided. short circuiting validation
  67. return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable)
  68. }
  69. if key, err = keyFunc(token); err != nil {
  70. // keyFunc returned an error
  71. if ve, ok := err.(*ValidationError); ok {
  72. return token, ve
  73. }
  74. return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
  75. }
  76. vErr := &ValidationError{}
  77. // Validate Claims
  78. if !p.SkipClaimsValidation {
  79. if err := token.Claims.Valid(); err != nil {
  80. // If the Claims Valid returned an error, check if it is a validation error,
  81. // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
  82. if e, ok := err.(*ValidationError); !ok {
  83. vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
  84. } else {
  85. vErr = e
  86. }
  87. }
  88. }
  89. // Perform validation
  90. token.Signature = parts[2]
  91. if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
  92. vErr.Inner = err
  93. vErr.Errors |= ValidationErrorSignatureInvalid
  94. }
  95. if vErr.valid() {
  96. token.Valid = true
  97. return token, nil
  98. }
  99. return token, vErr
  100. }
  101. // ParseUnverified parses the token but doesn't validate the signature.
  102. //
  103. // WARNING: Don't use this method unless you know what you're doing.
  104. //
  105. // It's only ever useful in cases where you know the signature is valid (because it has
  106. // been checked previously in the stack) and you want to extract values from it.
  107. func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) {
  108. parts = strings.Split(tokenString, ".")
  109. if len(parts) != 3 {
  110. return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
  111. }
  112. token = &Token{Raw: tokenString}
  113. // parse Header
  114. var headerBytes []byte
  115. if headerBytes, err = DecodeSegment(parts[0]); err != nil {
  116. if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
  117. return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
  118. }
  119. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  120. }
  121. if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
  122. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  123. }
  124. // parse Claims
  125. var claimBytes []byte
  126. token.Claims = claims
  127. if claimBytes, err = DecodeSegment(parts[1]); err != nil {
  128. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  129. }
  130. dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
  131. if p.UseJSONNumber {
  132. dec.UseNumber()
  133. }
  134. // JSON Decode. Special case for map type to avoid weird pointer behavior
  135. if c, ok := token.Claims.(MapClaims); ok {
  136. err = dec.Decode(&c)
  137. } else {
  138. err = dec.Decode(&claims)
  139. }
  140. // Handle decode error
  141. if err != nil {
  142. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  143. }
  144. // Lookup signature method
  145. if method, ok := token.Header["alg"].(string); ok {
  146. if token.Method = GetSigningMethod(method); token.Method == nil {
  147. return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
  148. }
  149. } else {
  150. return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
  151. }
  152. return token, parts, nil
  153. }