forked from jackwhelpton/fasthttp-routing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
301 lines (280 loc) · 9.83 KB
/
handlers.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package auth provides a set of user authentication handlers for the ozzo routing package.
package auth
import (
"encoding/base64"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/naharp/fasthttp-routing"
"github.com/valyala/fasthttp"
)
// User is the key used to store and retrieve the user identity information in routing.Context
const User = "User"
// Identity represents an authenticated user. If a user is successfully authenticated by
// an auth handler (Basic, Bearer, or Query), an Identity object will be made available for injection.
type Identity interface{}
// DefaultRealm is the default realm name for HTTP authentication. It is used by HTTP authentication based on
// Basic and Bearer.
var DefaultRealm = "API"
// BasicAuthFunc is the function that does the actual user authentication according to the given username and password.
type BasicAuthFunc func(c *routing.Context, username, password string) (Identity, error)
// Basic returns a routing.Handler that performs HTTP basic authentication.
// It can be used like the following:
//
// import (
// "errors"
// "fmt"
// "github.com/naharp/fasthttp-routing"
// "github.com/naharp/fasthttp-routing/auth"
// )
// func main() {
// r := routing.New()
// r.Use(auth.Basic(func(c *routing.Context, username, password string) (auth.Identity, error) {
// if username == "demo" && password == "foo" {
// return auth.Identity(username), nil
// }
// return nil, errors.New("invalid credential")
// }))
// r.Get("/demo", func(c *routing.Context) error {
// fmt.Fprintf(res, "Hello, %v", c.Get(auth.User))
// return nil
// })
// }
//
// By default, the auth realm is named as "API". You may customize it by specifying the realm parameter.
//
// When authentication fails, a "WWW-Authenticate" header will be sent, and a fasthttp.StatusUnauthorized
// error will be returned.
func Basic(fn BasicAuthFunc, realm ...string) routing.Handler {
name := DefaultRealm
if len(realm) > 0 {
name = realm[0]
}
return func(c *routing.Context) error {
username, password := parseBasicAuth(string(c.Request.Header.Peek("Authorization")))
identity, e := fn(c, username, password)
if e == nil {
c.Set(User, identity)
return nil
}
c.Response.Header.Set("WWW-Authenticate", `Basic realm="`+name+`"`)
return routing.NewHTTPError(fasthttp.StatusUnauthorized, e.Error())
}
}
func parseBasicAuth(auth string) (username, password string) {
if strings.HasPrefix(auth, "Basic ") {
if bytes, err := base64.StdEncoding.DecodeString(auth[6:]); err == nil {
str := string(bytes)
if i := strings.IndexByte(str, ':'); i >= 0 {
return str[:i], str[i+1:]
}
}
}
return
}
// TokenAuthFunc is the function for authenticating a user based on a secret token.
type TokenAuthFunc func(c *routing.Context, token string) (Identity, error)
// Bearer returns a routing.Handler that performs HTTP authentication based on bearer token.
// It can be used like the following:
//
// import (
// "errors"
// "fmt"
// "github.com/naharp/fasthttp-routing"
// "github.com/naharp/fasthttp-routing/auth"
// )
// func main() {
// r := routing.New()
// r.Use(auth.Bearer(func(c *routing.Context, token string) (auth.Identity, error) {
// if token == "secret" {
// return auth.Identity("demo"), nil
// }
// return nil, errors.New("invalid credential")
// }))
// r.Get("/demo", func(c *routing.Context) error {
// fmt.Fprintf(res, "Hello, %v", c.Get(auth.User))
// return nil
// })
// }
//
// By default, the auth realm is named as "API". You may customize it by specifying the realm parameter.
//
// When authentication fails, a "WWW-Authenticate" header will be sent, and a fasthttp.StatusUnauthorized
// error will be returned.
func Bearer(fn TokenAuthFunc, realm ...string) routing.Handler {
name := DefaultRealm
if len(realm) > 0 {
name = realm[0]
}
return func(c *routing.Context) error {
token := parseBearerAuth(string(c.Request.Header.Peek("Authorization")))
identity, e := fn(c, token)
if e == nil {
c.Set(User, identity)
return nil
}
c.Response.Header.Set("WWW-Authenticate", `Bearer realm="`+name+`"`)
return routing.NewHTTPError(fasthttp.StatusUnauthorized, e.Error())
}
}
func parseBearerAuth(auth string) string {
if strings.HasPrefix(auth, "Bearer ") {
if bearer, err := base64.StdEncoding.DecodeString(auth[7:]); err == nil {
return string(bearer)
}
}
return ""
}
// TokenName is the query parameter name for auth token.
var TokenName = "access-token"
// Query returns a routing.Handler that performs authentication based on a token passed via a query parameter.
// It can be used like the following:
//
// import (
// "errors"
// "fmt"
// "net/http"
// "github.com/naharp/fasthttp-routing"
// "github.com/naharp/fasthttp-routing/auth"
// )
// func main() {
// r := routing.New()
// r.Use(auth.Query(func(token string) (auth.Identity, error) {
// if token == "secret" {
// return auth.Identity("demo"), nil
// }
// return nil, errors.New("invalid credential")
// }))
// r.Get("/demo", func(c *routing.Context) error {
// fmt.Fprintf(res, "Hello, %v", c.Get(auth.User))
// return nil
// })
// }
//
// When authentication fails, a fasthttp.StatusUnauthorized error will be returned.
func Query(fn TokenAuthFunc, tokenName ...string) routing.Handler {
name := TokenName
if len(tokenName) > 0 {
name = tokenName[0]
}
return func(c *routing.Context) error {
token := string(c.QueryArgs().Peek(name))
identity, err := fn(c, token)
if err != nil {
return routing.NewHTTPError(fasthttp.StatusUnauthorized, err.Error())
}
c.Set(User, identity)
return nil
}
}
// JWTTokenHandler handles the parsed JWT token.
type JWTTokenHandler func(*routing.Context, *jwt.Token) error
// VerificationKeyHandler gets a dynamic VerificationKey.
type VerificationKeyHandler func(*routing.Context) string
// JWTOptions represents the options that can be used with the JWT handler.
type JWTOptions struct {
// auth realm. Defaults to "API".
Realm string
// the allowed signing method. This is required and should be the actual method that you use to create JWT token. It defaults to "HS256".
SigningMethod string
// a function that handles the parsed JWT token. Defaults to DefaultJWTTokenHandler, which stores the token in the routing context with the key "JWT".
TokenHandler JWTTokenHandler
// a function to get a dynamic VerificationKey
GetVerificationKey VerificationKeyHandler
}
// DefaultJWTTokenHandler stores the parsed JWT token in the routing context with the key named "JWT".
func DefaultJWTTokenHandler(c *routing.Context, token *jwt.Token) error {
c.Set("JWT", token)
return nil
}
// JWT returns a JWT (JSON Web Token) handler which attempts to parse the Bearer header into a JWT token and validate it.
// If both are successful, it will call a JWTTokenHandler to further handle the token. By default, the token
// will be stored in the routing context with the key named "JWT". Other handlers can retrieve this token to obtain
// the user identity information.
// If the parsing or validation fails, a "WWW-Authenticate" header will be sent, and a fasthttp.StatusUnauthorized
// error will be returned.
//
// JWT can be used like the following:
//
// import (
// "errors"
// "fmt"
// "github.com/dgrijalva/jwt-go"
// "github.com/naharp/fasthttp-routing"
// "github.com/naharp/fasthttp-routing/auth"
// )
// func main() {
// signingKey := "secret-key"
// r := routing.New()
//
// r.Get("/login", func(c *routing.Context) error {
// id, err := authenticate(c)
// if err != nil {
// return err
// }
// token, err := auth.NewJWT(jwt.MapClaims{
// "id": id
// }, signingKey)
// if err != nil {
// return err
// }
// return c.Write(token)
// })
//
// r.Use(auth.JWT(signingKey))
// r.Get("/restricted", func(c *routing.Context) error {
// claims := c.Get("JWT").(*jwt.Token).Claims.(jwt.MapClaims)
// return c.Write(fmt.Sprint("Welcome, %v!", claims["id"]))
// })
// }
func JWT(verificationKey string, options ...JWTOptions) routing.Handler {
var opt JWTOptions
if len(options) > 0 {
opt = options[0]
}
if opt.Realm == "" {
opt.Realm = DefaultRealm
}
if opt.SigningMethod == "" {
opt.SigningMethod = "HS256"
}
if opt.TokenHandler == nil {
opt.TokenHandler = DefaultJWTTokenHandler
}
parser := &jwt.Parser{
ValidMethods: []string{opt.SigningMethod},
}
return func(c *routing.Context) error {
header := string(c.Request.Header.Peek("Authorization"))
message := ""
if opt.GetVerificationKey != nil {
verificationKey = opt.GetVerificationKey(c)
}
if strings.HasPrefix(header, "Bearer ") {
token, err := parser.Parse(header[7:], func(t *jwt.Token) (interface{}, error) { return []byte(verificationKey), nil })
if err == nil && token.Valid {
err = opt.TokenHandler(c, token)
}
if err == nil {
return nil
}
message = err.Error()
}
c.Response.Header.Set("WWW-Authenticate", `Bearer realm="`+opt.Realm+`"`)
if message != "" {
return routing.NewHTTPError(fasthttp.StatusUnauthorized, message)
}
return routing.NewHTTPError(fasthttp.StatusUnauthorized)
}
}
// NewJWT creates a new JWT token and returns it as a signed string that may be sent to the client side.
// The signingMethod parameter is optional. It defaults to the HS256 algorithm.
func NewJWT(claims jwt.Claims, signingKey string, signingMethod ...jwt.SigningMethod) (string, error) {
var sm jwt.SigningMethod = jwt.SigningMethodHS256
if len(signingMethod) > 0 {
sm = signingMethod[0]
}
return jwt.NewWithClaims(sm, claims).SignedString([]byte(signingKey))
}