This repository has been archived by the owner on May 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
jwt.go
60 lines (52 loc) · 1.6 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
package jwtware
import (
"errors"
"strings"
"github.com/gofiber/fiber/v2"
)
var (
// ErrJWTMissingOrMalformed is returned when the JWT is missing or malformed.
ErrJWTMissingOrMalformed = errors.New("missing or malformed JWT")
)
type jwtExtractor func(c *fiber.Ctx) (string, error)
// 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 strings.TrimSpace(auth[l:]), nil
}
return "", ErrJWTMissingOrMalformed
}
}
// 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 "", ErrJWTMissingOrMalformed
}
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 "", ErrJWTMissingOrMalformed
}
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 "", ErrJWTMissingOrMalformed
}
return token, nil
}
}