go-zero中JWT的加密于解密

Go 复制代码
package jwt

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

type (
	TokenOptions struct {
		AccessSecret string
		AccessExpire int64
		Fields       map[string]interface{}
	}
	Token struct {
		AccessToken  string `json:"access_token"`
		AccessExpire int64  `json:"access_expire"`
	}
)

func BuildTokens(opt TokenOptions) (Token, error) {
	var token Token
	now := time.Now().Add(-time.Minute).Unix()
	accessToken, err := getJwtToken(opt.AccessSecret, now, opt.AccessExpire, opt.Fields)
	if err != nil {
		return token, nil
	}
	token.AccessExpire = now + opt.AccessExpire
	token.AccessToken = accessToken
	return token, nil
}

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间,单位秒
// @payload: 数据载体
func getJwtToken(secretKey string, iat, seconds int64, payload map[string]interface{}) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	for k, v := range payload {
		claims[k] = v
	}
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// ParseToken 解析 JWT
// @tokenString: 加密的token
// @mc: 解密后反写的实体  所以要传地址过去 方便反写
// t :  加密时的密钥
type claims struct {
	Mobile string
	jwt.MapClaims
}

func ParseToken(tokenString string, t string) (*claims, error) {
	mc := &claims{}
	// 解析token
	token, err := jwt.ParseWithClaims(tokenString, mc, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(t), nil
	})
	if err != nil {
		return nil, errors.New("JWT已过期")
	}
	if token.Valid { // 校验token
		return mc, nil
	}
	return mc, errors.New("token校验失败")
}

主要函数为getJwtToken(生成token)、ParseToken(解密token)

getJwtToken生成token传入了token的密钥、过期时间、想要包含的数据,为了解密后进行使用,这一块主要在登录的时候进行使用,手机号为唯一标识

Go 复制代码
token, tokenErr := jwt.BuildTokens(jwt.TokenOptions{
		AccessSecret: l.svcCtx.Config.Auth.AccessSecret,
		AccessExpire: l.svcCtx.Config.Auth.AccessExpire,
		Fields: map[string]interface{}{
			"mobile": req.Mobile,
		},
	})

ParseToken解密token接受加密后的token、密钥,解出来的就是当时加密想要包含的数据

这一块是中间件中进行了使用,将token解密后,拿到唯一标识,去redis中获取,如果存在说明么有过期,如果不存在,还没有写 哈哈 ,做个笔记 自己记录一下

Go 复制代码
package middleware

import (
	"fmt"
	"go/application/basics/internal/config"
	"go/application/basics/service/redisClient"
	"go/pkg/jwt"
	"net/http"
)

type AuthInterceptorMiddleware struct {
}

func NewAuthInterceptorMiddleware() *AuthInterceptorMiddleware {
	return &AuthInterceptorMiddleware{}
}

func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		authRequest := r.Header.Get("Authorization")
		if authRequest == "" {
			w.WriteHeader(http.StatusAccepted)
			w.Write([]byte("请登录"))
			return
		}
		authParse, authErr := jwt.ParseToken(authRequest, config.GlobalConfig.Auth.AccessSecret)
		if authErr != nil {
			w.WriteHeader(http.StatusAccepted)
			w.Write([]byte(authErr.Error()))
		}
		redis := redisClient.Init(config.GlobalConfig)
		fmt.Println("redis--------------------------")
		fmt.Println(redis)
		val, redisErr := redis.Get(authParse.Mobile).Result()
		fmt.Println(val)
		fmt.Println(redisErr)
		// Passthrough to next handler if need
		next(w, r)
	}
}
相关推荐
吃我一窝jio18 分钟前
Java Bug复盘与性能优化实战
java·开发语言·笔记
tong_li28 分钟前
给娃做个 AI 陪写作业助手:LangChain4j 入门(三):配本古诗书(RAG 入门),答得不瞎编
后端
用户48678952533901 小时前
多租户第二集:读隔离做完之后,写路径才是真坑
后端
bai2731 小时前
同一个 1.005,toFixed 给 1.00、Math.round 给 1、Intl 给 1.01:999 个三分位小数的实测
javascript·后端
千寻技术帮1 小时前
基于Spring Boot+Vue的农产品销售管理系统(源码+文档+数据库,附部署教程)
java·数据库·spring boot·后端·mysql·vue
码云社区1 小时前
Spring Boot陪诊陪护系统源码:医院目录、服务项目与城市业务配置
java·spring boot·后端·陪诊陪护·医院陪诊·医院陪护·陪护小程序
码云社区2 小时前
Spring Boot云快充协议源码:充电桩远程重启、参数配置与升级运维方案
运维·spring boot·后端·充电桩·充电系统·充电软件
Evand J2 小时前
【MATLAB例程】基于APF的多无人机动态路径规划与避障仿真。避碰及安全性能分析。附完整代码的下载链接
开发语言·matlab·无人机
Csvn2 小时前
Nginx 日志、监控与排障:全字段日志、条件日志与证据链定位
后端·nginx
鲸渔2 小时前
【AI Agent系列课程13-Python 基础13】JSON 读写:结构化数据交换基础
开发语言·python·json·ai编程