-
Notifications
You must be signed in to change notification settings - Fork 47
/
jwk_client.go
103 lines (80 loc) · 1.87 KB
/
jwk_client.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package auth0
import (
"sync"
"net/http"
"github.com/square/go-jose"
"strings"
"github.com/go-errors/errors"
"encoding/json"
)
type JWKClientOptions struct {
URI string
}
type JWKS struct {
Keys []jose.JsonWebKey `json:"keys"`
}
var (
DefaultOptions = JWKClientOptions{""}
ErrInvalidContentType = errors.New("Should have a JSON content type for JWKS endpoint.")
ErrNoKeyFound = errors.New("No Keys has been found")
ErrInvalidTokenHeader = errors.New("No valid header found")
ErrInvalidAlgorithm = errors.New("Only RS252 is supported")
)
type JWKClient struct {
keys map[string]jose.JsonWebKey
mu sync.Mutex
options JWKClientOptions
}
func NewJWKClient(options JWKClientOptions) *JWKClient{
return &JWKClient{keys: map[string]jose.JsonWebKey{}, options: options}
}
func (j *JWKClient) GetKey(ID string) (jose.JsonWebKey, bool) {
j.mu.Lock()
defer j.mu.Unlock()
key, exist := j.keys[ID]
if !exist {
j.downloadKeys()
}
key, exist = j.keys[ID]
return key, exist
}
func (j *JWKClient) downloadKeys() error {
resp, err := http.Get(j.options.URI)
if err != nil {
return err
}
defer resp.Body.Close()
if contentH := resp.Header.Get("Content-Type"); !strings.HasPrefix(contentH, "application/json") {
return ErrInvalidContentType
}
var jwks = JWKS{}
err = json.NewDecoder(resp.Body).Decode(&jwks)
if err != nil {
return err
}
if len(jwks.Keys) < 1 {
return ErrNoKeyFound
}
for _, key := range jwks.Keys {
j.keys[key.KeyID] = key
}
return nil
}
func (j *JWKClient) GetSecret(req *http.Request) (interface{}, error) {
t, err := FromHeader(req)
if err != nil {
return nil, err
}
if len(t.Headers) < 1 {
return nil, ErrInvalidTokenHeader
}
header := t.Headers[0]
if header.Algorithm != "RS256" {
return nil, ErrInvalidAlgorithm
}
webKey, exist := j.GetKey(header.KeyID)
if !exist {
return nil, ErrNoKeyFound
}
return webKey.Key, nil
}