|
| 1 | +package jwt |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/tls" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/dgrijalva/jwt-go" |
| 11 | + "github.com/lestrrat-go/jwx/jwk" |
| 12 | +) |
| 13 | + |
| 14 | +type KeyCache struct { |
| 15 | + url string |
| 16 | + http *http.Client |
| 17 | + m sync.Mutex |
| 18 | + keys *jwk.Set |
| 19 | +} |
| 20 | + |
| 21 | +func NewKeyCache(url string, tls *tls.Config) *KeyCache { |
| 22 | + t := http.DefaultTransport.(*http.Transport).Clone() |
| 23 | + t.MaxIdleConns = 100 |
| 24 | + t.MaxConnsPerHost = 100 |
| 25 | + t.MaxIdleConnsPerHost = 100 |
| 26 | + t.IdleConnTimeout = time.Second * 30 |
| 27 | + t.TLSClientConfig = tls |
| 28 | + client := &http.Client{ |
| 29 | + Transport: t, |
| 30 | + Timeout: time.Second * 10, |
| 31 | + } |
| 32 | + return &KeyCache{url: url, http: client} |
| 33 | +} |
| 34 | + |
| 35 | +func (c *KeyCache) GetOrFetchKey(token *jwt.Token) (interface{}, error) { |
| 36 | + if k, err := c.GetKey(token); err == nil { |
| 37 | + return k, nil |
| 38 | + } |
| 39 | + if err := c.FetchKeys(); err != nil { |
| 40 | + return nil, err |
| 41 | + } |
| 42 | + return c.GetKey(token) |
| 43 | +} |
| 44 | + |
| 45 | +func (c *KeyCache) GetKey(token *jwt.Token) (interface{}, error) { |
| 46 | + key, err := c.LookupKey(token) |
| 47 | + if err != nil { |
| 48 | + return nil, err |
| 49 | + } |
| 50 | + var v interface{} |
| 51 | + return v, key.Raw(&v) |
| 52 | +} |
| 53 | + |
| 54 | +func (c *KeyCache) LookupKey(token *jwt.Token) (jwk.Key, error) { |
| 55 | + id, ok := token.Header["kid"].(string) |
| 56 | + if !ok { |
| 57 | + return nil, fmt.Errorf("missing key id in token") |
| 58 | + } |
| 59 | + |
| 60 | + c.m.Lock() |
| 61 | + defer c.m.Unlock() |
| 62 | + |
| 63 | + if c.keys == nil { |
| 64 | + return nil, fmt.Errorf("empty JWK cache") |
| 65 | + } |
| 66 | + for _, key := range c.keys.LookupKeyID(id) { |
| 67 | + if key.Algorithm() == token.Method.Alg() { |
| 68 | + return key, nil |
| 69 | + } |
| 70 | + } |
| 71 | + return nil, fmt.Errorf("could not find JWK") |
| 72 | +} |
| 73 | + |
| 74 | +func (c *KeyCache) FetchKeys() error { |
| 75 | + keys, err := jwk.FetchHTTP(c.url, jwk.WithHTTPClient(c.http)) |
| 76 | + if err != nil { |
| 77 | + return fmt.Errorf("could not fetch JWK: %w", err) |
| 78 | + } |
| 79 | + |
| 80 | + c.m.Lock() |
| 81 | + defer c.m.Unlock() |
| 82 | + |
| 83 | + c.keys = keys |
| 84 | + return nil |
| 85 | +} |
0 commit comments