forked from gofiber/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
76 lines (68 loc) · 2.11 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package jwtware
import (
"errors"
"fmt"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
)
type jwtExtractor func(c *fiber.Ctx) (string, error)
// jwtKeyFunc returns a function that returns signing key for given token.
func jwtKeyFunc(config Config) jwt.Keyfunc {
return func(t *jwt.Token) (interface{}, error) {
// Check the signing method
if t.Method.Alg() != config.SigningMethod {
return nil, fmt.Errorf("Unexpected jwt signing method=%v", t.Header["alg"])
}
if len(config.SigningKeys) > 0 {
if kid, ok := t.Header["kid"].(string); ok {
if key, ok := config.SigningKeys[kid]; ok {
return key, nil
}
}
return nil, fmt.Errorf("Unexpected jwt key id=%v", t.Header["kid"])
}
return config.SigningKey, nil
}
}
// jwtFromHeader returns a function that extracts token from the request header.
func jwtFromHeader(header string, authScheme string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
auth := c.Get(header)
l := len(authScheme)
if len(auth) > l+1 && strings.EqualFold(auth[:l], authScheme) {
return auth[l+1:], nil
}
return "", errors.New("Missing or malformed JWT")
}
}
// jwtFromQuery returns a function that extracts token from the query string.
func jwtFromQuery(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Query(param)
if token == "" {
return "", errors.New("Missing or malformed JWT")
}
return token, nil
}
}
// jwtFromParam returns a function that extracts token from the url param string.
func jwtFromParam(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Params(param)
if token == "" {
return "", errors.New("Missing or malformed JWT")
}
return token, nil
}
}
// jwtFromCookie returns a function that extracts token from the named cookie.
func jwtFromCookie(name string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Cookies(name)
if token == "" {
return "", errors.New("Missing or malformed JWT")
}
return token, nil
}
}