parser.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
  37. token, parts, err := p.ParseUnverified(tokenString, claims)
  38. if err != nil {
  39. return token, err
  40. }
  41. // Verify signing method is in the required set
  42. if p.ValidMethods != nil {
  43. var signingMethodValid = false
  44. var alg = token.Method.Alg()
  45. for _, m := range p.ValidMethods {
  46. if m == alg {
  47. signingMethodValid = true
  48. break
  49. }
  50. }
  51. if !signingMethodValid {
  52. // signing method is not in the listed set
  53. return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid)
  54. }
  55. }
  56. // Lookup key
  57. var key interface{}
  58. if keyFunc == nil {
  59. // keyFunc was not provided. short circuiting validation
  60. return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable)
  61. }
  62. if key, err = keyFunc(token); err != nil {
  63. // keyFunc returned an error
  64. if ve, ok := err.(*ValidationError); ok {
  65. return token, ve
  66. }
  67. return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
  68. }
  69. vErr := &ValidationError{}
  70. // Validate Claims
  71. if !p.SkipClaimsValidation {
  72. if err := token.Claims.Valid(); err != nil {
  73. // If the Claims Valid returned an error, check if it is a validation error,
  74. // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
  75. if e, ok := err.(*ValidationError); !ok {
  76. vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
  77. } else {
  78. vErr = e
  79. }
  80. }
  81. }
  82. // Perform validation
  83. token.Signature = parts[2]
  84. if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
  85. vErr.Inner = err
  86. vErr.Errors |= ValidationErrorSignatureInvalid
  87. }
  88. if vErr.valid() {
  89. token.Valid = true
  90. return token, nil
  91. }
  92. return token, vErr
  93. }
  94. // ParseUnverified parses the token but doesn't validate the signature.
  95. //
  96. // WARNING: Don't use this method unless you know what you're doing.
  97. //
  98. // It's only ever useful in cases where you know the signature is valid (because it has
  99. // been checked previously in the stack) and you want to extract values from it.
  100. func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) {
  101. parts = strings.Split(tokenString, ".")
  102. if len(parts) != 3 {
  103. return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
  104. }
  105. token = &Token{Raw: tokenString}
  106. // parse Header
  107. var headerBytes []byte
  108. if headerBytes, err = DecodeSegment(parts[0]); err != nil {
  109. if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
  110. return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
  111. }
  112. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  113. }
  114. if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
  115. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  116. }
  117. // parse Claims
  118. var claimBytes []byte
  119. token.Claims = claims
  120. if claimBytes, err = DecodeSegment(parts[1]); err != nil {
  121. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  122. }
  123. dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
  124. if p.UseJSONNumber {
  125. dec.UseNumber()
  126. }
  127. // JSON Decode. Special case for map type to avoid weird pointer behavior
  128. if c, ok := token.Claims.(MapClaims); ok {
  129. err = dec.Decode(&c)
  130. } else {
  131. err = dec.Decode(&claims)
  132. }
  133. // Handle decode error
  134. if err != nil {
  135. return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
  136. }
  137. // Lookup signature method
  138. if method, ok := token.Header["alg"].(string); ok {
  139. if token.Method = GetSigningMethod(method); token.Method == nil {
  140. return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
  141. }
  142. } else {
  143. return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
  144. }
  145. return token, parts, nil
  146. }