-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
102 lines (91 loc) · 2.38 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package middleware
import (
"context"
"errors"
"github.com/cqqqq777/go-kitex-mall/shared/consts"
"github.com/cqqqq777/go-kitex-mall/shared/errz"
"net/http"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/golang-jwt/jwt"
)
var (
TokenExpired = errors.New("token is expired")
TokenNotValidYet = errors.New("token not active yet")
TokenMalformed = errors.New("that's not even a token")
TokenInvalid = errors.New("couldn't handle this token")
TokenNotFound = errors.New("no token")
)
func JwtAuth(secretKey string) app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
// get token
token := c.Query("token")
// check token
if token == "" {
c.JSON(http.StatusOK, utils.H{
"code": errz.CodeInvalidParam,
"msg": TokenNotFound.Error(),
})
}
j := NewJWT(secretKey)
claim, err := j.ParseToken(token)
if err != nil {
c.JSON(http.StatusOK, utils.H{
"code": errz.CodeTokenInvalid,
"msg": err.Error(),
})
c.Abort()
return
}
//set context
c.Set(consts.AccountID, claim.ID)
c.Set(consts.AccountIdentity, claim.Identity)
c.Next(ctx)
}
}
type JWT struct {
SigningKey []byte
}
type CustomClaims struct {
ID int64
Identity string
jwt.StandardClaims
}
func NewJWT(secretKey string) *JWT {
return &JWT{
SigningKey: []byte(secretKey),
}
}
// CreateToken to create a token
func (j *JWT) CreateToken(claims CustomClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.SigningKey)
}
// ParseToken to parse a token
func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return j.SigningKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
// Token is expired
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenInvalid
}
}
}
if token != nil {
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, TokenInvalid
} else {
return nil, TokenInvalid
}
}