Skip to content

Commit 908d356

Browse files
authored
feat: allow making exp claim required (#351)
1 parent 0cb4fa1 commit 908d356

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

parser_option.go

+8
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ func WithIssuedAt() ParserOption {
5858
}
5959
}
6060

61+
// WithExpirationRequired returns the ParserOption to make exp claim required.
62+
// By default exp claim is optional.
63+
funcWithExpirationRequired() ParserOption {
64+
returnfunc(p*Parser) {
65+
p.validator.requireExp=true
66+
}
67+
}
68+
6169
// WithAudience configures the validator to require the specified audience in
6270
// the `aud` claim. Validation will fail if the audience is not listed in the
6371
// token or the `aud` claim is missing.

parser_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,16 @@ var jwtTestData = []struct {
423423
jwt.NewParser(jwt.WithLeeway(2*time.Minute)),
424424
jwt.SigningMethodRS256,
425425
},
426+
{
427+
"rejects if exp is required but missing",
428+
"", // autogen
429+
defaultKeyFunc,
430+
&jwt.RegisteredClaims{},
431+
false,
432+
[]error{jwt.ErrTokenInvalidClaims},
433+
jwt.NewParser(jwt.WithExpirationRequired()),
434+
jwt.SigningMethodRS256,
435+
},
426436
}
427437

428438
// signToken creates and returns a signed JWT token using signingMethod.

validator.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ type validator struct {
4242
// validation. If unspecified, this defaults to time.Now.
4343
timeFuncfunc() time.Time
4444

45+
// requireExp specifies whether the exp claim is required
46+
requireExpbool
47+
4548
// verifyIat specifies whether the iat (Issued At) claim will be verified.
4649
// According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this
4750
// only specifies the age of the token, but no validation check is
@@ -86,8 +89,9 @@ func (v *validator) Validate(claims Claims) error {
8689
}
8790

8891
// We always need to check the expiration time, but usage of the claim
89-
// itself is OPTIONAL.
90-
iferr=v.verifyExpiresAt(claims, now, false); err!=nil {
92+
// itself is OPTIONAL by default. requireExp overrides this behavior
93+
// and makes the exp claim mandatory.
94+
iferr=v.verifyExpiresAt(claims, now, v.requireExp); err!=nil {
9195
errs=append(errs, err)
9296
}
9397

0 commit comments

Comments
 (0)
close