forked from hegemone/kore-poc
/
jwt.go
72 lines (65 loc) · 1.9 KB
/
jwt.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
package main
import (
"context"
"crypto/rsa"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware/security/jwt"
"github.com/hegemone/kore-poc/koredata-goa/app"
)
func NewJWTMiddleware() (goa.Middleware, error) {
keys, err := LoadJWTPublicKeys()
if err != nil {
return nil, err
}
return jwt.New(jwt.NewSimpleResolver(keys), ForceFail(), app.NewJWTSecurity()), nil
}
// JWTController implements the JWT resource.
type JWTController struct {
*goa.Controller
privateKey *rsa.PrivateKey
}
// LoadJWTPublicKeys loads PEM encoded RSA public keys used to validata and decrypt the JWT.
func LoadJWTPublicKeys() ([]jwt.Key, error) {
keyFiles, err := filepath.Glob("./jwtkey/*.pub")
if err != nil {
return nil, err
}
keys := make([]jwt.Key, len(keyFiles))
for i, keyFile := range keyFiles {
pem, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, err
}
key, err := jwtgo.ParseRSAPublicKeyFromPEM([]byte(pem))
if err != nil {
return nil, fmt.Errorf("failed to load key %s: %s", keyFile, err)
}
keys[i] = key
}
if len(keys) == 0 {
return nil, fmt.Errorf("couldn't load public keys for JWT security")
}
return keys, nil
}
// ForceFail is a middleware illustrating the use of validation middleware with JWT auth. It checks
// for the presence of a "fail" query string and fails validation if set to the value "true".
func ForceFail() goa.Middleware {
errValidationFailed := goa.NewErrorClass("validation_failed", 401)
forceFail := func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
if f, ok := req.URL.Query()["fail"]; ok {
if f[0] == "true" {
return errValidationFailed("forcing failure to illustrate Validation middleware")
}
}
return h(ctx, rw, req)
}
}
fm, _ := goa.NewMiddleware(forceFail)
return fm
}