forked from gofiber/contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
54 lines (46 loc) · 1.14 KB
/
jwt.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
package jwtware
import (
"reflect"
"github.com/gofiber/fiber/v3"
"github.com/golang-jwt/jwt/v5"
)
var (
defaultTokenLookup = "header:" + fiber.HeaderAuthorization
)
// New ...
func New(config ...Config) fiber.Handler {
cfg := makeCfg(config)
extractors := cfg.getExtractors()
// Return middleware handler
return func(c fiber.Ctx) error {
// Filter request to skip middleware
if cfg.Filter != nil && cfg.Filter(c) {
return c.Next()
}
var auth string
var err error
for _, extractor := range extractors {
auth, err = extractor(c)
if auth != "" && err == nil {
break
}
}
if err != nil {
return cfg.ErrorHandler(c, err)
}
var token *jwt.Token
if _, ok := cfg.Claims.(jwt.MapClaims); ok {
token, err = jwt.Parse(auth, cfg.KeyFunc)
} else {
t := reflect.ValueOf(cfg.Claims).Type().Elem()
claims := reflect.New(t).Interface().(jwt.Claims)
token, err = jwt.ParseWithClaims(auth, claims, cfg.KeyFunc)
}
if err == nil && token.Valid {
// Store user information from token into context.
c.Locals(cfg.ContextKey, token)
return cfg.SuccessHandler(c)
}
return cfg.ErrorHandler(c, err)
}
}