1.下载jwt
go get -u github.com/dgrijalva/jwt-go
2.新建生成token和解析token文件
2.1 新建common文件夹和jwtConfig文件夹 新建jwtconfig.go文件
2.2 jwtconfig.go文件代码
/*
@Time : 2021/8/2 下午3:03
@Author : mrxuexi
@File : main
@Software: GoLand
*/
package jwtConfig
import ("github.com/dgrijalva/jwt-go""time"
)type Claims struct {UserID int `json:"userId"`jwt.StandardClaims
}const expire_time = 30 * time.Minute
var jwtSecret = []byte("123")
// GenerateToken 生成token的函数
func GenerateToken(userId int) (string, error) {nowTime := time.Now()expireTime := nowTime.Add(expire_time)claims := Claims{userId, // 自行添加的信息jwt.StandardClaims{ExpiresAt: expireTime.Unix(), // 设置token过期时间Issuer: "admin", // 设置jwt签发者},}// 生成tokentokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)token, err := tokenClaims.SignedString(jwtSecret)return token, err
}// ParseToken 验证token的函数
func ParseToken(token string) (*Claims, error) {// 对token的密钥进行验证tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {return jwtSecret, nil})// 判断token是否过期if tokenClaims != nil {claims, _ := tokenClaims.Claims.(*Claims)return claims, nil}return nil, err
}
3.中间件封装文件
3.1 新建middleware文件夹和jwt.go文件
3.2 jwt.go文件代码
下图红色正方形框地址根据自己的项目定义
package middleware
import ("github.com/gin-gonic/gin""ListProject-ver1.0/common/jwtConfig""net/http""time"
)func JWT() gin.HandlerFunc {return func(context *gin.Context) {// 获取tokentoken := context.GetHeader("Token")if token == "" {context.JSON(http.StatusOK, gin.H{"code": http.StatusUnauthorized,"msg": "没有携带token","data": "",})context.Abort()return} else {claims, err := jwtConfig.ParseToken(token)if err != nil {context.JSON(http.StatusOK, gin.H{"code": http.StatusUnauthorized,"msg": "token验证失败","data": "",})context.Abort()return} else if time.Now().Unix() > claims.StandardClaims.ExpiresAt {context.JSON(http.StatusOK, gin.H{"code": http.StatusUnauthorized,"msg": "token已过期","data": "",})context.Abort()return}}}
}
4.调用测试中间件jwt功能
4.1 调用测试文件
4.2 代码
代码里面的ListProject-ver1.0/middleware这块也根据自己的项目引用
/*
@Time : 2021/8/2 下午3:03
@Author : mrxuexi
@File : main
@Software: GoLand
*/
package main
import ("github.com/gin-gonic/gin""ListProject-ver1.0/middleware"
)func main() {r := gin.Default()//注册组和中间件v1 := r.Group("/user"){v1.GET("/notoken",func(context *gin.Context) {context.String(http.StatusOK, "hello gin post method")})}//使用jwt中间件v2 := r.Group("/user2").Use(middleware.JWT()){v2.GET("/needtoken", func(context *gin.Context) {context.String(http.StatusOK, "hello gin post method")})}r.Run(":8888")
}
4.3 调试结果