jwt.go
1.1 KB
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
package utils
import (
"github.com/dgrijalva/jwt-go"
"time"
)
type UserTokenClaims struct {
UserId int64 `json:"userId"`
Phone string `json:"phone"`
jwt.StandardClaims
}
var jwtSecret = []byte("123456")
//解析 UserTokenClaims
func ParseJWTToken(token string) (*UserTokenClaims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &UserTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil {
return nil, err
}
if tokenClaims != nil {
if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid {
return claim, nil
}
}
return nil, err
}
//生成token
//@uid 用户变化
//@password 密码
//@expire 过期时长
func GenerateToken(uid int64, phone string, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: uid,
Phone: phone,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}