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

Commit 628223f

Browse files
authored
Merge pull request #220 from nelz9999/nelz/optional-date-claims
optional date claims
2 parents d312f7d + bc84b4d commit 628223f

File tree

2 files changed

+51
-10
lines changed

2 files changed

+51
-10
lines changed

jwt/validation.go

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,20 @@ func (c Claims) ValidateWithLeeway(e Expected, leeway time.Duration) error {
9494
}
9595
}
9696

97-
if !e.Time.IsZero() && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
98-
return ErrNotValidYet
99-
}
97+
if !e.Time.IsZero() {
98+
if c.NotBefore != nil && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
99+
return ErrNotValidYet
100+
}
100101

101-
if !e.Time.IsZero() && e.Time.Add(-leeway).After(c.Expiry.Time()) {
102-
return ErrExpired
103-
}
102+
if c.Expiry != nil && e.Time.Add(-leeway).After(c.Expiry.Time()) {
103+
return ErrExpired
104+
}
104105

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

111113
return nil

jwt/validation_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,42 @@ func TestIssuedInFuture(t *testing.T) {
126126
assert.Equal(t, err, ErrIssuedInTheFuture)
127127
}
128128
}
129+
130+
func TestOptionalDateClaims(t *testing.T) {
131+
var epoch time.Time
132+
133+
testCases := []struct {
134+
name string
135+
claim Claims
136+
want error
137+
}{
138+
{
139+
"no claims",
140+
Claims{},
141+
nil,
142+
},
143+
{
144+
"fail nbf",
145+
Claims{NotBefore: NewNumericDate(time.Now())},
146+
ErrNotValidYet,
147+
},
148+
{
149+
"fail exp",
150+
Claims{Expiry: NewNumericDate(epoch.Add(-7 * 24 * time.Hour))},
151+
ErrExpired,
152+
},
153+
{
154+
"fail iat",
155+
Claims{IssuedAt: NewNumericDate(time.Now())},
156+
ErrIssuedInTheFuture,
157+
},
158+
}
159+
160+
for _, tc := range testCases {
161+
t.Run(tc.name, func(t *testing.T) {
162+
expect := Expected{}.WithTime(epoch.Add(-24 * time.Hour))
163+
err := tc.claim.Validate(expect)
164+
assert.Equal(t, tc.want, err)
165+
})
166+
}
167+
}

0 commit comments

Comments
 (0)