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)
	}
}
相关推荐
减瓦10 分钟前
用 Git 为本地文件打造一台时光机
开发语言·git·编辑器
云浪11 分钟前
给 AI Agent 加上语音交互:ASR + 流式 TTS 实战
前端·人工智能·后端
卷无止境17 分钟前
当代码要上线前,谁在替你把关?——Python安全审查的方法论与实践
后端·python
冻柠檬飞冰走茶19 分钟前
PTA基础编程题目集 7-37 整数分解为若干项之和(C语言实现)
c语言·开发语言·数据结构·算法
卷无止境24 分钟前
Python Dataclasses:让类定义回归简洁的艺术
后端·python
FfHUCisI34 分钟前
Golang - 贪心算法 — 局部最优推导全局最优
贪心算法·golang·代理模式
末代iOS程序员华仔1 小时前
OPC + Flutter + Swift:跨平台应用上架与专业知识点获客实战指南
开发语言·flutter·swift
脚踏实地皮皮晨1 小时前
003004002_UniformGrid控件的使用方法
开发语言·c#·.net·wpf·visual studio
j7~2 小时前
【Linux】二十六.线程篇三《Linux多线程编程:线程控制、线程ID以及进程地址空间分布、线程局部存储__thread以及clone系统调用》---详解
linux·运维·服务器·开发语言·c++·多线程编辑·线程的控制