-
Notifications
You must be signed in to change notification settings - Fork 5
/
plugin.go
155 lines (127 loc) · 3.39 KB
/
plugin.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"strings"
jwt "github.com/dgrijalva/jwt-go"
"github.com/fagongzi/gateway/pkg/filter"
"github.com/valyala/fasthttp"
)
var (
errJWTMissing = errors.New("missing jwt token")
)
type tokenGetter func(filter.Context) (string, error)
func main() {}
// JWTCfg cfg
type JWTCfg struct {
Secret string `json:"secret"`
TokenLookup string `json:"tokenLookup"`
AuthScheme string `json:"authScheme"`
HeadPrefix string `json:"headPrefix"`
secretBytes []byte
}
// JWTFilter filter
type JWTFilter struct {
filter.BaseFilter
cfg JWTCfg
getter tokenGetter
}
// NewExternalFilter returns a filter
func NewExternalFilter() (filter.Filter, error) {
return &JWTFilter{}, nil
}
// Init init filter
func (f *JWTFilter) Init(cfg string) error {
data, err := ioutil.ReadFile(cfg)
if err != nil {
return err
}
err = json.Unmarshal(data, &f.cfg)
if err != nil {
return err
}
// Initialize
parts := strings.Split(f.cfg.TokenLookup, ":")
f.getter = jwtFromHeader(parts[1], f.cfg.AuthScheme)
switch parts[0] {
case "query":
f.getter = jwtFromQuery(parts[1])
case "cookie":
f.getter = jwtFromCookie(parts[1])
}
f.cfg.secretBytes = []byte(f.cfg.Secret)
return nil
}
// Name name
func (f *JWTFilter) Name() string {
return "JWT"
}
// Pre execute before proxy
func (f *JWTFilter) Pre(c filter.Context) (statusCode int, err error) {
if strings.ToUpper(c.API().AuthFilter) != f.Name() {
return f.BaseFilter.Pre(c)
}
token, err := f.getter(c)
if err != nil {
return fasthttp.StatusForbidden, err
}
claims, err := f.parseJWTToken(token)
if err != nil {
return fasthttp.StatusForbidden, err
}
for key, value := range claims {
c.ForwardRequest().Header.Add(fmt.Sprintf("%s%s", f.cfg.HeadPrefix, key), fmt.Sprintf("%v", value))
}
return f.BaseFilter.Pre(c)
}
// Post execute after proxy
func (f *JWTFilter) Post(c filter.Context) (statusCode int, err error) {
return f.BaseFilter.Post(c)
}
func (f *JWTFilter) parseJWTToken(tokenString string) (jwt.MapClaims, error) {
token, 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 f.cfg.secretBytes, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, fmt.Errorf("error jwt token")
}
func jwtFromHeader(header string, authScheme string) tokenGetter {
return func(c filter.Context) (string, error) {
auth := string(c.OriginRequest().Request.Header.Peek(header))
l := len(authScheme)
if len(auth) > l+1 && auth[:l] == authScheme {
return auth[l+1:], nil
}
return "", errJWTMissing
}
}
func jwtFromQuery(param string) tokenGetter {
return func(c filter.Context) (string, error) {
token := string(c.OriginRequest().Request.URI().QueryArgs().Peek(param))
if token == "" {
return "", errJWTMissing
}
return token, nil
}
}
func jwtFromCookie(name string) tokenGetter {
return func(c filter.Context) (string, error) {
value := string(c.OriginRequest().Request.Header.Cookie(name))
if len(value) == 0 {
return "", errJWTMissing
}
return value, nil
}
}