You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validator.go 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package jwt
  2. import (
  3. "crypto/subtle"
  4. "fmt"
  5. "time"
  6. )
  7. // ClaimsValidator is an interface that can be implemented by custom claims who
  8. // wish to execute any additional claims validation based on
  9. // application-specific logic. The Validate function is then executed in
  10. // addition to the regular claims validation and any error returned is appended
  11. // to the final validation result.
  12. //
  13. // type MyCustomClaims struct {
  14. // Foo string `json:"foo"`
  15. // jwt.RegisteredClaims
  16. // }
  17. //
  18. // func (m MyCustomClaims) Validate() error {
  19. // if m.Foo != "bar" {
  20. // return errors.New("must be foobar")
  21. // }
  22. // return nil
  23. // }
  24. type ClaimsValidator interface {
  25. Claims
  26. Validate() error
  27. }
  28. // Validator is the core of the new Validation API. It is automatically used by
  29. // a [Parser] during parsing and can be modified with various parser options.
  30. //
  31. // The [NewValidator] function should be used to create an instance of this
  32. // struct.
  33. type Validator struct {
  34. // leeway is an optional leeway that can be provided to account for clock skew.
  35. leeway time.Duration
  36. // timeFunc is used to supply the current time that is needed for
  37. // validation. If unspecified, this defaults to time.Now.
  38. timeFunc func() time.Time
  39. // requireExp specifies whether the exp claim is required
  40. requireExp bool
  41. // verifyIat specifies whether the iat (Issued At) claim will be verified.
  42. // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this
  43. // only specifies the age of the token, but no validation check is
  44. // necessary. However, if wanted, it can be checked if the iat is
  45. // unrealistic, i.e., in the future.
  46. verifyIat bool
  47. // expectedAud contains the audience this token expects. Supplying an empty
  48. // string will disable aud checking.
  49. expectedAud string
  50. // expectedIss contains the issuer this token expects. Supplying an empty
  51. // string will disable iss checking.
  52. expectedIss string
  53. // expectedSub contains the subject this token expects. Supplying an empty
  54. // string will disable sub checking.
  55. expectedSub string
  56. }
  57. // NewValidator can be used to create a stand-alone validator with the supplied
  58. // options. This validator can then be used to validate already parsed claims.
  59. //
  60. // Note: Under normal circumstances, explicitly creating a validator is not
  61. // needed and can potentially be dangerous; instead functions of the [Parser]
  62. // class should be used.
  63. //
  64. // The [Validator] is only checking the *validity* of the claims, such as its
  65. // expiration time, but it does NOT perform *signature verification* of the
  66. // token.
  67. func NewValidator(opts ...ParserOption) *Validator {
  68. p := NewParser(opts...)
  69. return p.validator
  70. }
  71. // Validate validates the given claims. It will also perform any custom
  72. // validation if claims implements the [ClaimsValidator] interface.
  73. //
  74. // Note: It will NOT perform any *signature verification* on the token that
  75. // contains the claims and expects that the [Claim] was already successfully
  76. // verified.
  77. func (v *Validator) Validate(claims Claims) error {
  78. var (
  79. now time.Time
  80. errs []error = make([]error, 0, 6)
  81. err error
  82. )
  83. // Check, if we have a time func
  84. if v.timeFunc != nil {
  85. now = v.timeFunc()
  86. } else {
  87. now = time.Now()
  88. }
  89. // We always need to check the expiration time, but usage of the claim
  90. // itself is OPTIONAL by default. requireExp overrides this behavior
  91. // and makes the exp claim mandatory.
  92. if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil {
  93. errs = append(errs, err)
  94. }
  95. // We always need to check not-before, but usage of the claim itself is
  96. // OPTIONAL.
  97. if err = v.verifyNotBefore(claims, now, false); err != nil {
  98. errs = append(errs, err)
  99. }
  100. // Check issued-at if the option is enabled
  101. if v.verifyIat {
  102. if err = v.verifyIssuedAt(claims, now, false); err != nil {
  103. errs = append(errs, err)
  104. }
  105. }
  106. // If we have an expected audience, we also require the audience claim
  107. if v.expectedAud != "" {
  108. if err = v.verifyAudience(claims, v.expectedAud, true); err != nil {
  109. errs = append(errs, err)
  110. }
  111. }
  112. // If we have an expected issuer, we also require the issuer claim
  113. if v.expectedIss != "" {
  114. if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil {
  115. errs = append(errs, err)
  116. }
  117. }
  118. // If we have an expected subject, we also require the subject claim
  119. if v.expectedSub != "" {
  120. if err = v.verifySubject(claims, v.expectedSub, true); err != nil {
  121. errs = append(errs, err)
  122. }
  123. }
  124. // Finally, we want to give the claim itself some possibility to do some
  125. // additional custom validation based on a custom Validate function.
  126. cvt, ok := claims.(ClaimsValidator)
  127. if ok {
  128. if err := cvt.Validate(); err != nil {
  129. errs = append(errs, err)
  130. }
  131. }
  132. if len(errs) == 0 {
  133. return nil
  134. }
  135. return joinErrors(errs...)
  136. }
  137. // verifyExpiresAt compares the exp claim in claims against cmp. This function
  138. // will succeed if cmp < exp. Additional leeway is taken into account.
  139. //
  140. // If exp is not set, it will succeed if the claim is not required,
  141. // otherwise ErrTokenRequiredClaimMissing will be returned.
  142. //
  143. // Additionally, if any error occurs while retrieving the claim, e.g., when its
  144. // the wrong type, an ErrTokenUnverifiable error will be returned.
  145. func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error {
  146. exp, err := claims.GetExpirationTime()
  147. if err != nil {
  148. return err
  149. }
  150. if exp == nil {
  151. return errorIfRequired(required, "exp")
  152. }
  153. return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired)
  154. }
  155. // verifyIssuedAt compares the iat claim in claims against cmp. This function
  156. // will succeed if cmp >= iat. Additional leeway is taken into account.
  157. //
  158. // If iat is not set, it will succeed if the claim is not required,
  159. // otherwise ErrTokenRequiredClaimMissing will be returned.
  160. //
  161. // Additionally, if any error occurs while retrieving the claim, e.g., when its
  162. // the wrong type, an ErrTokenUnverifiable error will be returned.
  163. func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error {
  164. iat, err := claims.GetIssuedAt()
  165. if err != nil {
  166. return err
  167. }
  168. if iat == nil {
  169. return errorIfRequired(required, "iat")
  170. }
  171. return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued)
  172. }
  173. // verifyNotBefore compares the nbf claim in claims against cmp. This function
  174. // will return true if cmp >= nbf. Additional leeway is taken into account.
  175. //
  176. // If nbf is not set, it will succeed if the claim is not required,
  177. // otherwise ErrTokenRequiredClaimMissing will be returned.
  178. //
  179. // Additionally, if any error occurs while retrieving the claim, e.g., when its
  180. // the wrong type, an ErrTokenUnverifiable error will be returned.
  181. func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error {
  182. nbf, err := claims.GetNotBefore()
  183. if err != nil {
  184. return err
  185. }
  186. if nbf == nil {
  187. return errorIfRequired(required, "nbf")
  188. }
  189. return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet)
  190. }
  191. // verifyAudience compares the aud claim against cmp.
  192. //
  193. // If aud is not set or an empty list, it will succeed if the claim is not required,
  194. // otherwise ErrTokenRequiredClaimMissing will be returned.
  195. //
  196. // Additionally, if any error occurs while retrieving the claim, e.g., when its
  197. // the wrong type, an ErrTokenUnverifiable error will be returned.
  198. func (v *Validator) verifyAudience(claims Claims, cmp string, required bool) error {
  199. aud, err := claims.GetAudience()
  200. if err != nil {
  201. return err
  202. }
  203. if len(aud) == 0 {
  204. return errorIfRequired(required, "aud")
  205. }
  206. // use a var here to keep constant time compare when looping over a number of claims
  207. result := false
  208. var stringClaims string
  209. for _, a := range aud {
  210. if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 {
  211. result = true
  212. }
  213. stringClaims = stringClaims + a
  214. }
  215. // case where "" is sent in one or many aud claims
  216. if stringClaims == "" {
  217. return errorIfRequired(required, "aud")
  218. }
  219. return errorIfFalse(result, ErrTokenInvalidAudience)
  220. }
  221. // verifyIssuer compares the iss claim in claims against cmp.
  222. //
  223. // If iss is not set, it will succeed if the claim is not required,
  224. // otherwise ErrTokenRequiredClaimMissing will be returned.
  225. //
  226. // Additionally, if any error occurs while retrieving the claim, e.g., when its
  227. // the wrong type, an ErrTokenUnverifiable error will be returned.
  228. func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error {
  229. iss, err := claims.GetIssuer()
  230. if err != nil {
  231. return err
  232. }
  233. if iss == "" {
  234. return errorIfRequired(required, "iss")
  235. }
  236. return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer)
  237. }
  238. // verifySubject compares the sub claim against cmp.
  239. //
  240. // If sub is not set, it will succeed if the claim is not required,
  241. // otherwise ErrTokenRequiredClaimMissing will be returned.
  242. //
  243. // Additionally, if any error occurs while retrieving the claim, e.g., when its
  244. // the wrong type, an ErrTokenUnverifiable error will be returned.
  245. func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error {
  246. sub, err := claims.GetSubject()
  247. if err != nil {
  248. return err
  249. }
  250. if sub == "" {
  251. return errorIfRequired(required, "sub")
  252. }
  253. return errorIfFalse(sub == cmp, ErrTokenInvalidSubject)
  254. }
  255. // errorIfFalse returns the error specified in err, if the value is true.
  256. // Otherwise, nil is returned.
  257. func errorIfFalse(value bool, err error) error {
  258. if value {
  259. return nil
  260. } else {
  261. return err
  262. }
  263. }
  264. // errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is
  265. // true. Otherwise, nil is returned.
  266. func errorIfRequired(required bool, claim string) error {
  267. if required {
  268. return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing)
  269. } else {
  270. return nil
  271. }
  272. }