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