Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

Commit

Permalink
Merge pull request #220 from nelz9999/nelz/optional-date-claims
Browse files Browse the repository at this point in the history
optional date claims
  • Loading branch information
csstaub committed Feb 26, 2019
2 parents d312f7d + bc84b4d commit 628223f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 10 deletions.
22 changes: 12 additions & 10 deletions jwt/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,20 @@ func (c Claims) ValidateWithLeeway(e Expected, leeway time.Duration) error {
}
}

if !e.Time.IsZero() && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
return ErrNotValidYet
}
if !e.Time.IsZero() {
if c.NotBefore != nil && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
return ErrNotValidYet
}

if !e.Time.IsZero() && e.Time.Add(-leeway).After(c.Expiry.Time()) {
return ErrExpired
}
if c.Expiry != nil && e.Time.Add(-leeway).After(c.Expiry.Time()) {
return ErrExpired
}

// IssuedAt is optional but cannot be in the future. This is not required by the RFC, but
// something is misconfigured if this happens and we should not trust it.
if !e.Time.IsZero() && e.Time.Add(leeway).Before(c.IssuedAt.Time()) {
return ErrIssuedInTheFuture
// IssuedAt is optional but cannot be in the future. This is not required by the RFC, but
// something is misconfigured if this happens and we should not trust it.
if c.IssuedAt != nil && e.Time.Add(leeway).Before(c.IssuedAt.Time()) {
return ErrIssuedInTheFuture
}
}

return nil
Expand Down
39 changes: 39 additions & 0 deletions jwt/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,42 @@ func TestIssuedInFuture(t *testing.T) {
assert.Equal(t, err, ErrIssuedInTheFuture)
}
}

func TestOptionalDateClaims(t *testing.T) {
var epoch time.Time

testCases := []struct {
name string
claim Claims
want error
}{
{
"no claims",
Claims{},
nil,
},
{
"fail nbf",
Claims{NotBefore: NewNumericDate(time.Now())},
ErrNotValidYet,
},
{
"fail exp",
Claims{Expiry: NewNumericDate(epoch.Add(-7 * 24 * time.Hour))},
ErrExpired,
},
{
"fail iat",
Claims{IssuedAt: NewNumericDate(time.Now())},
ErrIssuedInTheFuture,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
expect := Expected{}.WithTime(epoch.Add(-24 * time.Hour))
err := tc.claim.Validate(expect)
assert.Equal(t, tc.want, err)
})
}
}

0 comments on commit 628223f

Please sign in to comment.