-
Notifications
You must be signed in to change notification settings - Fork 63
/
jwt.go
44 lines (38 loc) · 1.01 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
package jwt
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/spf13/viper"
)
var jwtSecret = []byte(viper.GetString("server.jwtSecret"))
type Claims struct {
UserID int64 `json:"user_id"`
jwt.StandardClaims
}
// GenerateToken 签发用户Token
func GenerateToken(userID int64) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(24 * time.Hour)
claims := Claims{
UserID: userID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "38384-SearchEngine",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
// ParseToken 验证用户token
func ParseToken(token string) (*Claims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}