package middleware import ( "context" "log" "net/http" "time" "github.com/cloudwego/hertz/pkg/app" "github.com/hertz-contrib/jwt" ) var identityKey = "UserId" type loginForm struct { Account string `form:"username,required" json:"username,required"` Password string `form:"password,required" json:"password,required"` Type int `form:"type,required" json:"type,required"` } type User struct { UserId int64 } var hertzJWTMiddleware *jwt.HertzJWTMiddleware func init() { middleware, err := jwt.New(&jwt.HertzJWTMiddleware{ Realm: "test zone", Key: []byte("secret key"), Timeout: 30 * time.Minute, MaxRefresh: 30 * 24 * time.Hour, IdentityKey: identityKey, // Token负载信息 PayloadFunc: func(data interface{}) jwt.MapClaims { if v, ok := data.(*User); ok { return jwt.MapClaims{ identityKey: v.UserId, } } return jwt.MapClaims{} }, // 解析Token取出用户信息 IdentityHandler: func(ctx context.Context, c *app.RequestContext) interface{} { claims := jwt.ExtractClaims(ctx, c) return &User{ UserId: claims[identityKey].(int64), } }, // 登录 Authenticator: func(ctx context.Context, c *app.RequestContext) (interface{}, error) { c.Request.RequestURI() return nil, jwt.ErrFailedAuthentication }, // 权限控制 Authorizator: func(data interface{}, ctx context.Context, c *app.RequestContext) bool { return true }, // 未验证处理 Unauthorized: func(ctx context.Context, c *app.RequestContext, code int, message string) { c.JSON(code, map[string]interface{}{ "code": code, "message": message, }) }, // 登录响应 LoginResponse: func(ctx context.Context, c *app.RequestContext, code int, token string, expire time.Time) { c.JSON(http.StatusOK, map[string]interface{}{ "code": http.StatusOK, "token": token, "expire": expire.Format(time.RFC3339), }) }, // 登出响应 LogoutResponse: func(ctx context.Context, c *app.RequestContext, code int) { c.JSON(http.StatusOK, map[string]interface{}{ "code": http.StatusOK, }) }, // 刷新Token RefreshResponse: func(ctx context.Context, c *app.RequestContext, code int, token string, expire time.Time) { c.JSON(http.StatusOK, map[string]interface{}{ "code": http.StatusOK, "token": token, "expire": expire.Format(time.RFC3339), }) }, TokenLookup: "header: Authorization", }) if err != nil { log.Fatal("JWT Error:" + err.Error()) } hertzJWTMiddleware = middleware } func JWT() *jwt.HertzJWTMiddleware { return hertzJWTMiddleware }