package jwtauth import ( "WchimeGinSystem/conf" "errors" "time" "github.com/golang-jwt/jwt/v5" ) type MyClaims struct { jwt.RegisteredClaims UserId int64 } func CreateToken(userId int64) (string, error) { claims := MyClaims{ UserId: userId, RegisteredClaims: jwt.RegisteredClaims{ NotBefore: jwt.NewNumericDate(time.Now()), ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)), Issuer: "wchime", }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return token.SignedString([]byte(conf.SECRET)) } func ParserToken(tokenStr string) (*MyClaims, error) { claims := &MyClaims{} token, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (interface{}, error) { return []byte(conf.SECRET), nil }) if token == nil || !token.Valid { return nil, errors.New("token错误") } return claims, err }
封装生成和验证token方法
package middleware import ( "fmt" "WchimeGinSystem/conf" "WchimeGinSystem/utils" "WchimeGinSystem/utils/cache" "WchimeGinSystem/utils/errmsg" jwtauth "WchimeGinSystem/utils/jwtAuth" "strings" "time" "github.com/gin-gonic/gin" "github.com/go-redis/redis/v8" ) func JWTAuth() gin.HandlerFunc { return func(ctx *gin.Context) { tokenHeader := ctx.Request.Header.Get("Authorization") if tokenHeader == "" { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_TOKEN_VALID, "") ctx.Abort() return } checkToken := strings.Split(tokenHeader, " ") if len(checkToken) != 2 || checkToken[0] != "Bearer" { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_TOKEN_VALID, "") ctx.Abort() return } claims, err := jwtauth.ParserToken(checkToken[1]) if err != nil { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_TOKEN_VALID, "") ctx.Abort() return } login_k := fmt.Sprintf("%s_%s", conf.SERVER_NAME, string(claims.UserId)) val, err := cache.RDB.Get(cache.CTX, login_k).Result() if val != checkToken[1] { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_TOKEN_VALID, "") ctx.Abort() return } if err == redis.Nil { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_TOKEN_VALID, "") ctx.Abort() return } else if err != nil { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_BASE, "") ctx.Abort() return } err = cache.RDB.Set(cache.CTX, login_k, checkToken[1], 7200*time.Second).Err() if err != nil { utils.RespContext(ctx).ErrorResp(nil, errmsg.ERROR_BASE, "") return } ctx.Set("user", claims) ctx.Next() } }
使用中间件进行验证。
项目地址:https://gitee.com/mom925/gin-system
标签:err,return,jwt,nil,验证,ctx,utils,JWT,gin From: https://www.cnblogs.com/moon3496694/p/18549127