jwt.go
1.2 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
package common
import (
"time"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"github.com/dgrijalva/jwt-go"
)
type UserTokenClaims struct {
Username string `json:"username"`
Password string `json:"password"`
jwt.StandardClaims
}
var jwtSecret = []byte("123456")
//解析 UserTokenClaims
func ParseJWTToken(token string) (*UserTokenClaims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &UserTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil {
return nil, err
}
if tokenClaims != nil {
if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid {
log.Info("ParseJWTToken:%s -> %v", token, claim)
return claim, nil
}
}
return nil, err
}
func GenerateToken(username, password string) (string, error) {
now := time.Now()
expireTime := now.Add(3 * time.Hour)
claims := UserTokenClaims{
Username: username,
Password: password,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}