-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
62 lines (54 loc) · 1.28 KB
/
jwt.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
package jt
import (
"errors"
"github.com/dgrijalva/jwt-go"
"sync"
"time"
)
var (
EXPIRE time.Duration
SECRET string
lazyClimsInstance *JwtClaims
once sync.Once
)
type JwtClaims struct {
ID interface{} `json:"id"`
Username string `json:"username"`
jwt.StandardClaims
}
func NewJwtInstance(expire time.Duration, secret string) *JwtClaims {
if lazyClimsInstance == nil {
once.Do(func() {
EXPIRE = expire
SECRET = secret
lazyClimsInstance = &JwtClaims{}
})
}
return lazyClimsInstance
}
// GenerateToken 签发Token
func (j *JwtClaims) GenerateToken(claims *JwtClaims) (string, error) {
c := JwtClaims{
ID: claims.ID,
Username: claims.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(EXPIRE).Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
return token.SignedString([]byte(SECRET))
}
// ParseToken 解析TOKEN
func (j *JwtClaims) ParseToken(token string) (*JwtClaims, error) {
t, err := jwt.ParseWithClaims(token, &JwtClaims{},
func(token *jwt.Token) (interface{}, error) {
return []byte(SECRET), nil
})
if err != nil {
return nil, err
}
if claims, ok := t.Claims.(*JwtClaims); ok && t.Valid {
return claims, nil
}
return nil, errors.New("invalid token")
}