jwt.go
1.3 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
56
57
58
59
60
61
62
63
64
65
66
package lib
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
var (
key []byte = []byte("sx87sda0w7x7sd")
JWtExpiresSecond int64 = 60 * 60 * 12
)
//MyToken ...
type MyToken struct {
jwt.StandardClaims
UID int64 `json:"uid"` //管理员的id
}
func NewMyToken(id int64) *MyToken {
return &MyToken{UID: id}
}
//CreateJWTToken ...
func (mytoken *MyToken) CreateJWTToken() (string, error) {
nowTime := time.Now().Unix()
mytoken.StandardClaims = jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: nowTime + JWtExpiresSecond,
Issuer: "mmm_partnermg",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, mytoken)
return token.SignedString(key)
}
//ValidJWTToken ...
func (mytoken *MyToken) 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
}
getoken, ok := token.Claims.(*MyToken)
if ok && token.Valid {
// 验证成功,返回信息
return getoken, nil
}
// 验证失败
return nil, fmt.Errorf("token Valid fail")
}
func (mytoken *MyToken) IsJwtErrorExpired(err error) bool {
ve, ok := err.(*jwt.ValidationError)
if ok && ve.Errors == jwt.ValidationErrorExpired {
return true
}
return false
}