1 回答
TA贡献1777条经验 获得超10个赞
我从一开始就告诉过你,当你想生成 JWT 时,请执行以下操作:
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
// This is the information which frontend can use
// The backend can also decode the token and get admin etc.
claims := token.Claims.(jwt.MapClaims)
claims["username"] = ID
accessTokenExpireTime := time.Now().Add(time.Hour * 48).Unix()
claims["exp"] = accessTokenExpireTime
// Generate encoded token and send it as response.
// The signing string should be secret (a generated UUID works too)
t, err := token.SignedString([]byte("AccessToken"))
然后当你想解码用户名时,请执行以下操作:
type MyCustomClaims struct {
Username string `json:"username"`
jwt.StandardClaims
}
auth := c.Request.Header.Get("Authorization")
if auth == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Authorization Header Not Found"})
return
}
splitToken := strings.Split(auth, "Bearer ")
auth = splitToken[1]
token, err := jwt.ParseWithClaims(auth, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("AccessToken"), nil
})
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Token is wrong or Expire"})
return
}
if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
log.Printf("%v %v", claims.Username, claims.StandardClaims.ExpiresAt)
}
- 1 回答
- 0 关注
- 285 浏览
添加回答
举报