1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| package middleware
import ( "errors" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt" "go.uber.org/zap" "net/http" "time" "v1/go-import-template/global" "v1/go-import-template/model/request" "v1/go-import-template/model/response" )
func JWTAuthMiddleware() func(ctx *gin.Context) { return func(ctx *gin.Context) { token := getToken(ctx) global.GvaLogger.Sugar().Infof("token: %s", token) if token == "" { response.Error(ctx, "Token不能为空!") ctx.Abort() return } userClaim, err := ParseToken(token) if err != nil { response.ErrorWithToken(ctx, "Token error :"+err.Error()) ctx.Abort() return } setContextData(ctx, userClaim, token) ctx.Next() } }
func setContextData(ctx *gin.Context, userClaim *request.UserClaims, token string) { }
func getToken(ctx *gin.Context) string { var token string token = ctx.Request.Header.Get("TOKEN") if token != "" { return token } if ctx.Request.Method == http.MethodGet { token, ok := ctx.GetQuery("token") if ok { return token } } if ctx.Request.Method == http.MethodPost { postParam := make(map[string]interface{}) _ = ctx.ShouldBindJSON(&postParam) token, ok := postParam["token"] if ok { return token.(string) } } return "" }
func CreateToken(uid uint) (string, error) { newWithClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, &request.UserClaims{ StandardClaims: &jwt.StandardClaims{ ExpiresAt: time.Now().Add(global.GvaConfig.Jwt.Expire).Unix(), Issuer: global.GvaConfig.Jwt.Issuer, IssuedAt: time.Now().Unix(), }, Uid: uid, }) return newWithClaims.SignedString([]byte(global.GvaConfig.Jwt.Secret)) }
func ParseToken(tokenString string) (*request.UserClaims, error) { var err error var token *jwt.Token token, err = jwt.ParseWithClaims(tokenString, &request.UserClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(global.GvaConfig.Jwt.Secret), nil }) if err != nil { global.GvaLogger.Error("解析JWT失败", zap.String("error", err.Error())) return nil, err } userClaims, ok := token.Claims.(*request.UserClaims) if !ok || !token.Valid { return nil, errors.New("JWT验证失败") } return userClaims, nil }
|