-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
89 lines (75 loc) · 2.1 KB
/
main.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
package main
import (
"crypto/rand"
"crypto/rsa"
"net/http"
jwt2 "github.com/golang-jwt/jwt"
"github.com/foomo/keel"
"github.com/foomo/keel/jwt"
"github.com/foomo/keel/log"
"github.com/foomo/keel/net/http/middleware"
httputils "github.com/foomo/keel/utils/net/http"
)
func main() {
svr := keel.NewServer()
// get logger
l := svr.Logger()
contextKey := "custom"
type CustomClaims struct {
jwt2.StandardClaims
Name string `json:"name"`
}
// generate rsa key
rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
log.Must(l, err, "")
// create jwt key
jwtKey := jwt.NewKey("demo", &rsaKey.PublicKey, rsaKey)
log.Must(l, err, "failed to create jwt key")
// init jwt with key files
jwtInst := jwt.New(jwtKey)
// custom token provider
tokenProvider := middleware.HeaderTokenProvider(
middleware.HeaderTokenProviderWithPrefix("Custom "),
middleware.HeaderTokenProviderWithHeader("X-Authorization"),
)
// create demo service
svs := http.NewServeMux()
svs.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// retrieve from context
if claims, ok := r.Context().Value(contextKey).(*CustomClaims); ok {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(claims.Name))
}
})
svs.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
if token, err := jwtInst.GetSignedToken(CustomClaims{
StandardClaims: jwt.NewStandardClaims(),
Name: "JWT From Token Example",
}); err != nil {
httputils.InternalServerError(l, w, r, err)
} else {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(token))
}
})
svr.AddService(
keel.NewServiceHTTP(l, "demo", "localhost:8080", svs,
middleware.Skip(
middleware.JWT(
jwtInst,
contextKey,
// require token
middleware.JWTWithMissingTokenHandler(middleware.RequiredJWTMissingTokenHandler),
// use custom token provider
middleware.JWTWithTokenProvider(tokenProvider),
// user custom claims
middleware.JWTWithClaimsProvider(func() jwt2.Claims {
return &CustomClaims{}
}),
),
middleware.RequestURIWhitelistSkipper("/token"),
),
),
)
svr.Run()
}