-
Notifications
You must be signed in to change notification settings - Fork 36
/
json_token_validator.go
67 lines (59 loc) · 2.05 KB
/
json_token_validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package paseto
import (
"time"
errors "golang.org/x/xerrors"
)
// Validator defines a JSONToken validator function.
type Validator func(token *JSONToken) error
// ForAudience validates that the JSONToken audience has the specified value.
func ForAudience(audience string) Validator {
return func(token *JSONToken) error {
if token.Audience != audience {
return errors.Errorf(`token was not intended for "%s" audience: %w`, audience, ErrTokenValidationError)
}
return nil
}
}
// IdentifiedBy validates that the JSONToken JTI has the specified value.
func IdentifiedBy(jti string) Validator {
return func(token *JSONToken) error {
if token.Jti != jti {
return errors.Errorf(`token was expected to be identified by "%s": %w`, jti, ErrTokenValidationError)
}
return nil
}
}
// IssuedBy validates that the JSONToken issuer has the specified value.
func IssuedBy(issuer string) Validator {
return func(token *JSONToken) error {
if token.Issuer != issuer {
return errors.Errorf(`token was not issued by "%s": %w`, issuer, ErrTokenValidationError)
}
return nil
}
}
// Subject validates that the JSONToken subject has the specified value.
func Subject(subject string) Validator {
return func(token *JSONToken) error {
if token.Subject != subject {
return errors.Errorf(`token was not related to subject "%s": %w`, subject, ErrTokenValidationError)
}
return nil
}
}
// ValidAt validates whether the token is valid at the specified time, based on
// the values of the IssuedAt, NotBefore and Expiration claims in the token.
func ValidAt(t time.Time) Validator {
return func(token *JSONToken) error {
if !token.IssuedAt.IsZero() && t.Before(token.IssuedAt) {
return errors.Errorf("token was issued in the future: %w", ErrTokenValidationError)
}
if !token.NotBefore.IsZero() && t.Before(token.NotBefore) {
return errors.Errorf("token cannot be used yet: %w", ErrTokenValidationError)
}
if !token.Expiration.IsZero() && t.After(token.Expiration) {
return errors.Errorf("token has expired: %w", ErrTokenValidationError)
}
return nil
}
}