jwt.go
1.0 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
53
54
55
package utils
import (
"fmt"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var (
key = []byte("sx87sda0w7x7sd")
)
//MyToken ...
type MyToken struct {
jwt.StandardClaims
UID int `json:"uid"`
CompanyID int `json:"company_id"`
}
//CreateJWTToken ...
func CreateJWTToken(id int) (string, error) {
nowTime := time.Now().Unix()
claims := MyToken{
StandardClaims: jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: 60 * 60 * 2, //过期时间
Issuer: "test_a",
},
UID: id,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(key)
}
//ValidJWTToken ...
func ValidJWTToken(tokenString string) (*MyToken, error) {
token, err := jwt.ParseWithClaims(
tokenString,
&MyToken{},
func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*MyToken); ok && token.Valid {
// 验证成功,返回信息
return claims, nil
}
// 验证失败
return nil, fmt.Errorf("token Valid fail")
}