1.引入包"github.com/dgrijalva/jwt-go"
2.设置token并返回
func setToken() string {
token := jwt.New(jwt.SigningMethodHS256)
claims := make(jwt.MapClaims)
claims[“exp”] = time.Now().Add(time.Hour * time.Duration(1)).Unix() // 设置超时时间
claims[“iat”] = time.Now().Unix()
token.Claims = claims
tokenString, err := token.SignedString([]byte(“mobile”))
if err != nil {
return “”
}
return tokenString
}
3.获取校验token
token, err := request.ParseFromRequest(c.Request, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (i interface{}, e error) {
return []byte(“mobile”), nil
})
if err == nil {
if token.Valid {
// token有效可以进行其他操作
} else {
fmt.Println(“Token is not vaild”) // token无效
}
} else {
fmt.Println( “unauthorized access to this resource”) // 未找到token
}
网友评论