Merge pull request #227 from jzelinskie/fixjwt

jwt: add updateKeys method and call in constructor
This commit is contained in:
Jimmy Zelinskie 2016-09-26 21:34:10 -04:00 committed by GitHub
commit 8a71ee793d
2 changed files with 43 additions and 28 deletions

View file

@ -78,7 +78,11 @@ func (cfg ConfigFile) CreateHooks() (preHooks, postHooks []middleware.Hook, err
if err != nil { if err != nil {
return nil, nil, errors.New("invalid JWT middleware config: " + err.Error()) return nil, nil, errors.New("invalid JWT middleware config: " + err.Error())
} }
preHooks = append(preHooks, jwt.NewHook(jwtCfg)) hook, err := jwt.NewHook(jwtCfg)
if err != nil {
return nil, nil, errors.New("invalid JWT middleware config: " + err.Error())
}
preHooks = append(preHooks, hook)
case "client approval": case "client approval":
var caCfg clientapproval.Config var caCfg clientapproval.Config
err := yaml.Unmarshal(cfgBytes, &caCfg) err := yaml.Unmarshal(cfgBytes, &caCfg)

View file

@ -50,23 +50,37 @@ type hook struct {
} }
// NewHook returns an instance of the JWT middleware. // NewHook returns an instance of the JWT middleware.
func NewHook(cfg Config) middleware.Hook { func NewHook(cfg Config) (middleware.Hook, error) {
h := &hook{ h := &hook{
cfg: cfg, cfg: cfg,
publicKeys: map[string]crypto.PublicKey{}, publicKeys: map[string]crypto.PublicKey{},
closing: make(chan struct{}), closing: make(chan struct{}),
} }
err := h.updateKeys()
if err != nil {
return nil, errors.New("failed to update initial JWK Set: " + err.Error())
}
go func() { go func() {
for { for {
select { select {
case <-h.closing: case <-h.closing:
return return
case <-time.After(cfg.JWKUpdateInterval): case <-time.After(cfg.JWKUpdateInterval):
resp, err := http.Get(cfg.JWKSetURL) h.updateKeys()
}
}
}()
return h, nil
}
func (h *hook) updateKeys() error {
resp, err := http.Get(h.cfg.JWKSetURL)
if err != nil { if err != nil {
log.Errorln("failed to fetch JWK Set: " + err.Error()) log.Errorln("failed to fetch JWK Set: " + err.Error())
continue return err
} }
parsedJWKs := map[string]gojwk.Key{} parsedJWKs := map[string]gojwk.Key{}
@ -74,7 +88,7 @@ func NewHook(cfg Config) middleware.Hook {
if err != nil { if err != nil {
resp.Body.Close() resp.Body.Close()
log.Errorln("failed to decode JWK JSON: " + err.Error()) log.Errorln("failed to decode JWK JSON: " + err.Error())
continue return err
} }
resp.Body.Close() resp.Body.Close()
@ -83,16 +97,13 @@ func NewHook(cfg Config) middleware.Hook {
publicKey, err := parsedJWK.DecodePublicKey() publicKey, err := parsedJWK.DecodePublicKey()
if err != nil { if err != nil {
log.Errorln("failed to decode JWK into public key: " + err.Error()) log.Errorln("failed to decode JWK into public key: " + err.Error())
continue return err
} }
keys[kid] = publicKey keys[kid] = publicKey
} }
h.publicKeys = keys h.publicKeys = keys
}
}
}()
return h return nil
} }
func (h *hook) Stop() <-chan error { func (h *hook) Stop() <-chan error {