新建request文件
package modelsimport "github.com/dgrijalva/jwt-go"type CustomClaims struct {ID uintNickName stringAuthorityId uintjwt.StandardClaims}
生成key
https://suijimimashengcheng.bmcx.com/
编写token中间件
package middlewaresimport ("errors""go_final/mxshop-api/global""go_final/mxshop-api/models""net/http""time""github.com/dgrijalva/jwt-go""github.com/gin-gonic/gin")type JWT struct {SigningKey []byte}var (TokenExpired = errors.New("token is expired")TokenNotValidYet = errors.New("token not active yet")TokenMalformed = errors.New("that's not even a token")TokenInvalid = errors.New("couldn't handle this token"))func NewJWT() *JWT {return &JWT{[]byte(global.ServerConfig.JWTInfo.SigningKey), //可以设置过期时间}}func JWTAuth() gin.HandlerFunc {return func(c *gin.Context) {// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localSstorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录token := c.Request.Header.Get("authorization")if token == "" {c.JSON(http.StatusUnauthorized, map[string]string{"msg": "请登录后操作",})c.Abort()return}j := NewJWT()// parseToken 解析token包含的信息claims, err := j.ParseToken(token)if err != nil {if err == TokenExpired {c.JSON(http.StatusUnauthorized, gin.H{"msg": "授权已过期",})c.Abort()return}c.JSON(http.StatusUnauthorized, "未登陆")c.Abort()return}c.Set("claims", claims)c.Set("userId", claims.ID)c.Next()}}// CreateToken 创建一个tokenfunc (j *JWT) CreateToken(claims models.CustomClaims) (string, error) {token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)return token.SignedString(j.SigningKey)}// ParseToken 解析tokenfunc (j *JWT) ParseToken(tokenString string) (*models.CustomClaims, error) {token, err := jwt.ParseWithClaims(tokenString, &models.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {return j.SigningKey, nil})if err != nil {if ve, ok := err.(*jwt.ValidationError); ok {if ve.Errors&jwt.ValidationErrorMalformed != 0 {return nil, TokenMalformed} else if ve.Errors&jwt.ValidationErrorExpired != 0 {// Token is expiredreturn nil, TokenExpired} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {return nil, TokenNotValidYet} else {return nil, TokenInvalid}}}if token != nil {if claims, ok := token.Claims.(*models.CustomClaims); ok && token.Valid {return claims, nil}return nil, TokenInvalid} else {return nil, TokenInvalid}}// RefreshToken 更新tokenfunc (j *JWT) RefreshToken(tokenString string) (string, error) {jwt.TimeFunc = func() time.Time {return time.Unix(0, 0)}token, err := jwt.ParseWithClaims(tokenString, &models.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {return j.SigningKey, nil})if err != nil {return "", err}if claims, ok := token.Claims.(*models.CustomClaims); ok && token.Valid {jwt.TimeFunc = time.Nowclaims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()return j.CreateToken(*claims)}return "", TokenInvalid}
使用(生成带签名的token)
jwt := middlewares.NewJWT()claims := models.CustomClaims{ID: uint(userInfo.ID),NickName: userInfo.NickName,AuthorityId: uint(userInfo.Role),StandardClaims: jwt2.StandardClaims{NotBefore: time.Now().Unix(), // 签名的生效时间ExpiresAt: time.Now().Unix() + 60*60*24*7, // 签名过期时间Issuer: "Felix_Mxshop",},}token, err := jwt.CreateToken(claims)if err != nil {// 生成token失败}
