-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
jwx.go
265 lines (227 loc) · 6.16 KB
/
jwx.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package jwx
import (
"errors"
"fmt"
"strings"
"github.com/labstack/echo/v4"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jwt"
)
var (
// DefaultConfig is the default JWX auth middleware config.
DefaultConfig = Config{
Skipper: DefaultSkipper,
SignatureAlgorithm: jwa.HS256,
ContextKey: "user",
TokenLookup: "header:" + echo.HeaderAuthorization,
AuthScheme: "Bearer",
TokenFactory: defaultTokenFactory,
}
)
func defaultTokenFactory(_ echo.Context) jwt.Token {
return jwt.New()
}
func (config *Config) handleError(err error, c echo.Context) (error, bool) {
if h := config.ErrorHandler; h != nil {
return h(err), true
}
if h := config.ErrorHandlerWithContext; h != nil {
return h(err, c), true
}
return nil, false
}
func (config *Config) parseToken(auth string, c echo.Context) (jwt.Token, error) {
token := config.TokenFactory(c)
var options []jwt.ParseOption
options = append(options, jwt.WithToken(token))
ks := config.KeySet
key := config.Key
if kf := config.KeyFunc; kf != nil {
thing, err := kf(c)
if err != nil {
return nil, err // ooooh, the urge to wrap...
}
switch v := thing.(type) {
case jwk.Set:
ks = v
case jwk.Key:
key = v
default:
return nil, fmt.Errorf(`invalid value for KeyFunc return value: %T`, v)
}
}
if ks != nil {
options = append(options, jwt.WithKeySet(ks))
} else if key != nil {
alg := jwa.SignatureAlgorithm(key.Algorithm())
if alg == "" {
alg = config.SignatureAlgorithm
}
if alg == "" {
return nil, errors.New(`no signature algorithm could be inferred (did you set SignatureAlgorithm, or did you make sure the key has an 'alg' field?)`)
}
options = append(options, jwt.WithVerify(alg, key))
} else {
return nil, errors.New(`neither jwk.Key nor jwk.Set available`)
}
if len(config.ValidateOptions) > 0 {
options = append(options, jwt.WithValidate(true))
}
for _, option := range config.ValidateOptions {
options = append(options, option)
}
if _, err := jwt.ParseString(auth, options...); err != nil {
return nil, err
}
return token, nil
}
func JWX(v interface{}) echo.MiddlewareFunc {
config := DefaultConfig
switch v := v.(type) {
case jwk.Set:
config.KeySet = v
case jwk.Key:
config.Key = v
case func(echo.Context) (interface{},error):
config.KeyFunc = v
default:
panic(fmt.Sprintf("expected jwk.Key or jwk.Set or a KeyFunc: got %T", v))
}
return WithConfig(config)
}
func WithConfig(config Config) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultConfig.Skipper
}
if config.TokenFactory == nil {
config.TokenFactory = DefaultConfig.TokenFactory
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultConfig.TokenLookup
}
if config.AuthScheme == "" {
config.AuthScheme = DefaultConfig.AuthScheme
}
if config.SignatureAlgorithm == "" {
config.SignatureAlgorithm = DefaultConfig.SignatureAlgorithm
}
if config.ContextKey == "" {
config.ContextKey = DefaultConfig.ContextKey
}
sources := strings.Split(config.TokenLookup, ",")
var extractors []jwtExtractor
for _, source := range sources {
parts := strings.Split(source, ":")
switch parts[0] {
case "query":
extractors = append(extractors, jwxFromQuery(parts[1]))
case "param":
extractors = append(extractors, jwxFromParam(parts[1]))
case "cookie":
extractors = append(extractors, jwxFromCookie(parts[1]))
case "form":
extractors = append(extractors, jwxFromForm(parts[1]))
case "header":
extractors = append(extractors, jwxFromHeader(parts[1], config.AuthScheme))
}
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
if config.BeforeFunc != nil {
config.BeforeFunc(c)
}
var auth string
var err error
for _, extractor := range extractors {
// Extract token from extractor, if it's not fail break the loop and
// set auth
auth, err = extractor(c)
if err == nil {
break
}
}
// If none of extractor has a token, handle error
if err != nil {
if herr, ok := config.handleError(err, c); ok {
return herr
}
return err
}
if auth == "" {
panic("no auth")
}
token, err := config.parseToken(auth, c)
if err == nil {
// Store user information from token into context.
c.Set(config.ContextKey, token)
if config.SuccessHandler != nil {
config.SuccessHandler(c)
}
return next(c)
}
if herr, ok := config.handleError(err, c); ok {
return herr
}
return &echo.HTTPError{
Code: ErrJWTInvalid.Code,
Message: ErrJWTInvalid.Message,
Internal: err,
}
}
}
}
// jwxFromHeader returns a `jwtExtractor` that extracts token from the request header.
func jwxFromHeader(header string, authScheme string) jwtExtractor {
return func(c echo.Context) (string, error) {
auth := c.Request().Header.Get(header)
l := len(authScheme)
if len(auth) > l+1 && auth[:l] == authScheme {
return auth[l+1:], nil
}
return "", ErrJWTMissing
}
}
// jwxFromQuery returns a `jwtExtractor` that extracts token from the query string.
func jwxFromQuery(param string) jwtExtractor {
return func(c echo.Context) (string, error) {
token := c.QueryParam(param)
if token == "" {
return "", ErrJWTMissing
}
return token, nil
}
}
// jwxFromParam returns a `jwtExtractor` that extracts token from the url param string.
func jwxFromParam(param string) jwtExtractor {
return func(c echo.Context) (string, error) {
token := c.Param(param)
if token == "" {
return "", ErrJWTMissing
}
return token, nil
}
}
// jwxFromCookie returns a `jwtExtractor` that extracts token from the named cookie.
func jwxFromCookie(name string) jwtExtractor {
return func(c echo.Context) (string, error) {
cookie, err := c.Cookie(name)
if err != nil {
return "", ErrJWTMissing
}
return cookie.Value, nil
}
}
// jwxFromForm returns a `jwtExtractor` that extracts token from the form field.
func jwxFromForm(name string) jwtExtractor {
return func(c echo.Context) (string, error) {
field := c.FormValue(name)
if field == "" {
return "", ErrJWTMissing
}
return field, nil
}
}