-
Notifications
You must be signed in to change notification settings - Fork 0
/
JToken.go
83 lines (61 loc) · 1.72 KB
/
JToken.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
package toolset
import (
"time"
"github.com/golang-jwt/jwt/v5"
)
type JClaims struct {
jwt.RegisteredClaims
}
type LoginClaims struct {
AppId string `json:"appId"`
jwt.RegisteredClaims
}
// const accessTokenExpire = time.Hour * 24 * 7
// const refreshTokenExpire = time.Hour * 24 * 30
func GetToken(secretKey string, accessExpire time.Duration, refreshExpire time.Duration) (string, string, error) {
accessToken, err := generateToken(accessExpire, secretKey)
if err != nil {
return "", "", err
}
refreshToken, err := generateToken(refreshExpire, secretKey)
if err != nil {
return "", "", err
}
return accessToken, refreshToken, nil
}
func ParseAccessToken(token string, secretKey string) (*JClaims, error) {
t, err := jwt.ParseWithClaims(token, &JClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
claims, ok := t.Claims.(*JClaims)
if ok && t.Valid {
return claims, nil
} else {
return nil, err
}
}
func VerifyLoginToken(token string, secretKey string, appId string) bool {
t, err := jwt.ParseWithClaims(token, &LoginClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil {
return false
}
claims, ok := t.Claims.(*LoginClaims)
if ok && t.Valid {
return claims.AppId == appId
} else {
return false
}
}
func generateToken(expire time.Duration, secretKey string) (string, error) {
claims := JClaims{
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expire)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}
accessToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secretKey))
return accessToken, err
}