-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
validator.go
70 lines (57 loc) · 1.38 KB
/
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
68
69
70
package jwt
import (
"context"
"fmt"
"github.com/golang-jwt/jwt/v4"
)
type Validator struct {
keys *KeyCache
}
var errMissingToken = fmt.Errorf("missing token")
func NewValidator(keyCache *KeyCache) *Validator {
return &Validator{keys: keyCache}
}
func errParseToken(err error) error {
return fmt.Errorf("could not parse token: %w", err)
}
func (v *Validator) Parse(token string) (jwt.MapClaims, error) {
if token == "" {
return nil, errMissingToken
}
t, err := jwt.Parse(token, v.keys.GetOrFetchKey)
if t == nil {
return nil, errParseToken(err)
}
c := t.Claims.(jwt.MapClaims)
if err != nil {
return c, errParseToken(err)
}
return c, nil
}
func (v *Validator) ParseWithContext(ctx context.Context, token string) (jwt.MapClaims, error) {
if token == "" {
return nil, errMissingToken
}
jwtKeyfunc := func(token *jwt.Token) (interface{}, error) {
return v.keys.GetOrFetchKeyWithContext(ctx, token)
}
t, err := jwt.Parse(token, jwtKeyfunc)
if err != nil {
return nil, errParseToken(err)
}
c, ok := t.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("unsupported type %T", t.Claims)
}
return c, nil
}
func (v *Validator) ParseWithClaims(token string, claims jwt.Claims) error {
if token == "" {
return errMissingToken
}
_, err := jwt.ParseWithClaims(token, claims, v.keys.GetOrFetchKey)
if err != nil {
return errParseToken(err)
}
return nil
}