欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Go-zero:JWT鉴权方式

Go-zero:JWT鉴权方式

2025/4/19 11:31:18 来源:https://blog.csdn.net/qq_41460537/article/details/147283591  浏览:    关键词:Go-zero:JWT鉴权方式

1.简述

用于记录在go-zero的后端项目中如何添加jwt中间件鉴权

2.流程

配置api.yaml

Auth:AccessSecret: "secret_key"AccessExpire: 604800

config中添加Auth结构体

Auth struct {AccessSecret stringAccessExpire int64
}

types定义jwt token的自定义数据结构,这里以用户登录信息的UserClaims做例子,在types中新建userclaims.go文件

type UserClaims struct {UserUID int64  `json:"user_uid"`Role    string `json:"role"`jwt.RegisteredClaims
}

中间件方法:在middleware文件夹下建立jwtmiddleware.go用来储存创立和返回jwt中间件

1.jwt中间件结构体,包含一个secret字段用来实现jwt验签

// jwt中间件结构体,包含一个secret字段,用于jwt验签
type JWTMiddleware struct {Secret string
}

2.创建jwtmiddleware的实例

// 工厂方法,用于创建和返回JWTMiddleware实力
func NewJWTMiddleware(secret string) *JWTMiddleware {return &JWTMiddleware{Secret: secret}
}

3.中间件签名,接收一个函数handler,获取请求头中的token并解析,然后送入另一个handler

// 中间件签名,接受一个下一个处理的函数,返回另一个处理函数
func (m *JWTMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {//获取请求头中的tokentokenStr := r.Header.Get("Authorization")if tokenStr == "" {http.Error(w, "Missing token", http.StatusUnauthorized)return}//解析token并绑定自定义结构体UserClaimstoken, err := jwt.ParseWithClaims(tokenStr, &types.UserClaims{}, func(token *jwt.Token) (interface{}, error) {return []byte(m.Secret), nil})//检查是否有效if err != nil || !token.Valid {http.Error(w, "Invalid token", http.StatusUnauthorized)return}// 将解析结果保存进 contextif claims, ok := token.Claims.(*types.UserClaims); ok {ctx := context.WithValue(r.Context(), "user_uid", claims.UserUID)ctx = context.WithValue(ctx, "role", claims.Role)r = r.WithContext(ctx)}next(w, r)}
}

servicecontext中注册并初始化jwt中间件


type ServiceContext struct {Config        config.ConfigDB            *gorm.DBUserModel     model.IUserModelJWTMiddleware *middleware.JWTMiddleware
}func NewServiceContext(c config.Config) *ServiceContext {db, err := gorm.Open(mysql.Open(c.Mysql.DataSource), &gorm.Config{})if err != nil {panic("connect failed : " + err.Error())}_ = db.AutoMigrate(&model.User{},&model.Post{},&model.Comment{},&model.Like{},&model.Report{},&model.Section{},&model.SearchModel{},&model.InstallationStatus{})return &ServiceContext{Config:        c,DB:            db,JWTMiddleware: middleware.NewJWTMiddleware(c.Auth.AccessSecret),}}

routes中给要使用jwt的api进行包装(这里还没写需要用的api,大概语法如下)

//初始化中间件
jwtMW := middleware.NewJWTMiddleware(secret_key)
//包装需要用的api
server.AddRoutes([]rest.Route{{Method:  http.MethodPost,Path:    "/api/user_info",Handler: jwtMW.Handle(GetUserInfo(user_uid)),},},)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词