-
Notifications
You must be signed in to change notification settings - Fork 122
/
token.go
76 lines (64 loc) · 1.68 KB
/
token.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 token
import (
"log"
"time"
jwt "github.com/dgrijalva/jwt-go"
config "github.com/micro/go-micro/config"
"github.com/micro/go-micro/config/source/file"
)
// CustomClaims 自定义的 metadata在加密后作为 JWT 的第二部分返回给客户端
type CustomClaims struct {
UserName string `json:"user_name"`
UserID string `json:"user_id"`
PerAddr string `json:"per_addr"`
Roles []string `json:"roles"`
jwt.StandardClaims
}
// Token jwt服务
var privateKey []byte
// InitConfig 初始化
func InitConfig(filePath string, path ...string) {
fileSource := file.NewSource(
file.WithPath(filePath),
)
conf := config.NewConfig()
err := conf.Load(fileSource)
if err != nil {
log.Fatal(err)
}
privateKey = conf.Get(path...).Bytes()
if err != nil {
log.Fatal(err)
}
}
//Decode 解码
func Decode(tokenStr string) (*CustomClaims, error) {
t, err := jwt.ParseWithClaims(tokenStr, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return privateKey, nil
})
if err != nil {
return nil, err
}
// 解密转换类型并返回
if claims, ok := t.Claims.(*CustomClaims); ok && t.Valid {
return claims, nil
}
return nil, err
}
// Encode 将 User 用户信息加密为 JWT 字符串
// expireTime := time.Now().Add(time.Hour * 24 * 3).Unix() 三天后过期
func Encode(userName, userID, perAddr string, roles []string, issuer string, expireTime int64) (string, error) {
claims := CustomClaims{
userName,
userID,
perAddr,
roles,
jwt.StandardClaims{
Issuer: issuer,
IssuedAt: time.Now().Unix(),
ExpiresAt: expireTime,
},
}
jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return jwtToken.SignedString(privateKey)
}