-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
jwt.go
46 lines (38 loc) · 939 Bytes
/
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
package jwt
import (
"time"
jwt "github.com/golang-jwt/jwt"
)
type Claims struct {
UserName string `json:"username"`
PassWord string `json:"password"`
jwt.StandardClaims
}
var jwtSecret []byte
//创建token
func GenerateToken(username, password string) (string, error) {
expireTime := time.Now().AddDate(999, 0, 0)
clims := Claims{
username,
password,
jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "gin-blog",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, clims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
//解析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 clims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return clims, nil
}
}
return nil, err
}