JWT
PPG007 ... 2021-12-26 Less than 1 minute
# JWT
func generateToken(username string, secret string, period time.Duration) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &UserClaim{
username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(period).Unix(),
},
})
tokenString, err := token.SignedString([]byte(secret))
if err != nil {
log.Println(err)
return "", fmt.Errorf("cannot generate token")
}
return tokenString, nil
}
func VerifyToken(tokenString string) error {
token, _ := jwt.ParseWithClaims(tokenString, &UserClaim{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("invalid token sign method")
}
return []byte(secret), nil
})
if _, ok := token.Claims.(*UserClaim); ok && token.Valid {
return nil
}
return fmt.Errorf("invalid token")
}
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
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