-
Notifications
You must be signed in to change notification settings - Fork 5
/
jwt-token-example.go
85 lines (65 loc) · 1.91 KB
/
jwt-token-example.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"log"
"time"
"github.com/golang-jwt/jwt"
"github.com/pkg/errors"
)
func main() {
username := "zouying"
token, err := genToken(username)
if err != nil {
log.Fatalf("generate token failed: %v", err)
}
log.Printf("username=%s token=%s", username, token)
claims, err := parseToken(token)
if err != nil {
log.Fatalf("username=%s token=%s parse token error: %v", username, token, err)
}
log.Printf("username=%s token=%s claims: %+v", username, token, claims)
// --- 等待延期 ---
time.Sleep(TokenExpireDuration)
time.Sleep(3 * time.Second)
log.Printf("------------ After token expired ---------")
claims, err = parseToken(token) // error: token is expired
if err != nil {
v, ok := err.(*jwt.ValidationError)
if ok && v.Errors == jwt.ValidationErrorExpired {
log.Printf("username=%s token=%s expired", username, token)
return
}
log.Fatalf("username=%s token=%s parse token error: %v", username, token, err)
}
log.Printf("username=%s token=%s claims: %+v", username, token, claims)
}
type MyClaims struct {
Username string `json:"username"`
jwt.StandardClaims
}
// const TokenExpireDuration = time.Hour
const TokenExpireDuration = time.Second * 10
var MySecret = []byte("AllYourBase")
func genToken(username string) (string, error) {
c := MyClaims{
username,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(),
Issuer: "my-project",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
return token.SignedString(MySecret)
}
func parseToken(tokenString string) (*MyClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(t *jwt.Token) (interface{}, error) {
return MySecret, nil
})
if err != nil {
// log.Fatalf("parse with clains error: %v", err)
return nil, err
}
if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New("invalid token")
}