-
Notifications
You must be signed in to change notification settings - Fork 87
/
jwt-middleware.go
executable file
·75 lines (64 loc) · 1.9 KB
/
jwt-middleware.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
package main
import (
"context"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/journeymidnight/yig/helper"
"net/http"
"strings"
)
type JwtMiddleware struct {
handler http.Handler
}
func FromAuthHeader(r *http.Request) (string, error) {
authHeader, ok := r.Header["Authorization"]
helper.Logger.Info("authHeader:", authHeader)
if ok == false || authHeader[0] == "" {
return "", nil // No error, just no token
}
authHeaderParts := strings.Split(authHeader[0], " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
return "", fmt.Errorf("Authorization header format must be Bearer {token}")
}
return authHeaderParts[1], nil
}
func (m *JwtMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
tokenString, err := FromAuthHeader(r)
if err != nil {
w.WriteHeader(400)
return
}
parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(helper.CONFIG.AdminKey), nil
})
if err != nil {
w.WriteHeader(401)
return
}
if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
var userKey string = "claims"
ctx := context.WithValue(r.Context(), userKey, claims)
m.handler.ServeHTTP(w, r.WithContext(ctx))
return
} else {
w.WriteHeader(401)
return
}
}
func SetJwtMiddlewareHandler(handler http.Handler) http.Handler {
jwtChecker := &JwtMiddleware{
handler: handler,
}
return jwtChecker
}
func SetJwtMiddlewareFunc(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
jwtChecker := &JwtMiddleware{
handler: http.HandlerFunc(f),
}
return jwtChecker.ServeHTTP
}