JWT鉴权中,可以使用context获取存储的信息
需求:在生成jwt的时候,保存UserID。并在解析jwt数据的时候,获取到UserID。
生成token代码
var CtxKeyJwtUserId = "jwtUserId"
func (l *GenerateTokenLogic) getJwtToken(secretKey string, iat, seconds, userId int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
claims[ctxData.CtxKeyJwtUserId] = userId // 存入userId
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
}
获取userId代码
func GetUidFromCtx(ctx context.Context) int64 {
var uid int64
if jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(json.Number); ok {
if int64Uid, err := jsonUid.Int64(); err == nil {
uid = int64Uid
} else {
logx.WithContext(ctx).Errorf("GetUidFromCtx err : %+v", err)
}
}
return uid
}
解析
前提
需要在api文件中对应方法前面加上 : jwt:xxxx
go-zero从jwt token解析后会将用户生成token时传入的kv原封不动的放在http.Request的Context中,因此我们可以通过Context就可以拿到你想要的值