feat: allow making exp claim required (#351)

This commit is contained in:
Tarek Sharafi 2023-10-09 20:58:20 +03:00 committed by GitHub
parent 0cb4fa15e3
commit 908d356713
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 2 deletions

View File

@ -58,6 +58,14 @@ func WithIssuedAt() ParserOption {
} }
} }
// WithExpirationRequired returns the ParserOption to make exp claim required.
// By default exp claim is optional.
func WithExpirationRequired() ParserOption {
return func(p *Parser) {
p.validator.requireExp = true
}
}
// WithAudience configures the validator to require the specified audience in // WithAudience configures the validator to require the specified audience in
// the `aud` claim. Validation will fail if the audience is not listed in the // the `aud` claim. Validation will fail if the audience is not listed in the
// token or the `aud` claim is missing. // token or the `aud` claim is missing.

View File

@ -423,6 +423,16 @@ var jwtTestData = []struct {
jwt.NewParser(jwt.WithLeeway(2 * time.Minute)), jwt.NewParser(jwt.WithLeeway(2 * time.Minute)),
jwt.SigningMethodRS256, jwt.SigningMethodRS256,
}, },
{
"rejects if exp is required but missing",
"", // autogen
defaultKeyFunc,
&jwt.RegisteredClaims{},
false,
[]error{jwt.ErrTokenInvalidClaims},
jwt.NewParser(jwt.WithExpirationRequired()),
jwt.SigningMethodRS256,
},
} }
// signToken creates and returns a signed JWT token using signingMethod. // signToken creates and returns a signed JWT token using signingMethod.

View File

@ -42,6 +42,9 @@ type validator struct {
// validation. If unspecified, this defaults to time.Now. // validation. If unspecified, this defaults to time.Now.
timeFunc func() time.Time timeFunc func() time.Time
// requireExp specifies whether the exp claim is required
requireExp bool
// verifyIat specifies whether the iat (Issued At) claim will be verified. // verifyIat specifies whether the iat (Issued At) claim will be verified.
// According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this
// only specifies the age of the token, but no validation check is // only specifies the age of the token, but no validation check is
@ -86,8 +89,9 @@ func (v *validator) Validate(claims Claims) error {
} }
// We always need to check the expiration time, but usage of the claim // We always need to check the expiration time, but usage of the claim
// itself is OPTIONAL. // itself is OPTIONAL by default. requireExp overrides this behavior
if err = v.verifyExpiresAt(claims, now, false); err != nil { // and makes the exp claim mandatory.
if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil {
errs = append(errs, err) errs = append(errs, err)
} }