forked from xesina/golang-echo-realworld-example-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
82 lines (73 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
77
78
79
80
81
82
package middleware
import (
"fmt"
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
"github.com/faozimipa/golang-echo-realworld-example-app/utils"
)
type (
//JWTConfig struct
JWTConfig struct {
Skipper Skipper
SigningKey interface{}
}
//Skipper func
Skipper func(c echo.Context) bool
jwtExtractor func(echo.Context) (string, error)
)
var (
//ErrJWTMissing setter
ErrJWTMissing = echo.NewHTTPError(http.StatusUnauthorized, "missing or malformed jwt")
//ErrJWTInvalid setter
ErrJWTInvalid = echo.NewHTTPError(http.StatusForbidden, "invalid or expired jwt")
)
//JWT func
func JWT(key interface{}) echo.MiddlewareFunc {
c := JWTConfig{}
c.SigningKey = key
return JWTWithConfig(c)
}
//JWTWithConfig func
func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
extractor := jwtFromHeader("Authorization", "Token")
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
auth, err := extractor(c)
if err != nil {
if config.Skipper != nil {
if config.Skipper(c) {
return next(c)
}
}
return c.JSON(http.StatusUnauthorized, utils.NewError(err))
}
token, err := jwt.Parse(auth, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return config.SigningKey, nil
})
if err != nil {
return c.JSON(http.StatusForbidden, utils.NewError(ErrJWTInvalid))
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
userID := uint(claims["id"].(float64))
c.Set("user", userID)
return next(c)
}
return c.JSON(http.StatusForbidden, utils.NewError(ErrJWTInvalid))
}
}
}
// jwtFromHeader returns a `jwtExtractor` that extracts token from the request header.
func jwtFromHeader(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
}
}