``` go
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
)
var mySingningKey = []byte("secret")
func createToken() (string, error) {
claims := jwt.MapClaims{
"uid": "111111",
"exp": time.Now().Add(time.Second * 4).Unix(),
"iss": "auth.sunsl.net",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
getTokenRemainingValidity(claims["exp"])
tokenstring, err := token.SignedString(mySingningKey)
if err != nil {
return "", err
}
return tokenstring, nil
}
func RequireTokenAuthentication(tokenstring string) (bool, int) {
token, _ := jwt.ParseWithClaims(tokenstring, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("error")
}
return mySingningKey, nil
})
return token.Valid, getTokenRemainingValidity(token.Claims.(jwt.MapClaims)["exp"])
}
func getTokenRemainingValidity(timestamp interface{}) int {
if validity, ok := timestamp.(float64); ok {
tm := time.Unix(int64(validity), 0)
remainer := tm.Sub(time.Now())
if remainer > 0 {
fmt.Println("*")
return int(remainer.Seconds())
}
}
return -1
}
func main() {
tokenstring, _ := createToken()
valid, rtime := RequireTokenAuthentication(tokenstring)
fmt.Printf("1:%v:%v\n", valid, rtime)
time.Sleep(time.Second * 2)
valid, rtime = RequireTokenAuthentication(tokenstring)
fmt.Printf("2:%v:%v\n", valid, rtime)
time.Sleep(time.Second * 2)
valid, rtime = RequireTokenAuthentication(tokenstring)
fmt.Printf("3:%v:%v\n", valid, rtime)
time.Sleep(time.Second * 2)
valid, rtime = RequireTokenAuthentication(tokenstring)
fmt.Printf("4:%v:%v\n", valid, rtime)
time.Sleep(time.Second * 2)
valid, rtime = RequireTokenAuthentication(tokenstring)
fmt.Printf("5:%v:%v\n", valid, rtime)
}
```
结果如下:
```
[ `go run main.go` | done: 8.580037361s ]
1:true:3
2:true:1
3:true:-1
4:false:-1
5:false:-1
```
设定周期为4秒,每隔两秒获取一次检验,为什么第三次明明时效已过却还是返回true?
有疑问加站长微信联系(非本文作者)