gin 使用 Json Web Token(JWT)
发布于 2022-10-22 23:20:11阅读 1232
之前的token验证借助了redis,如果用jwt就不需要了
中间件
cat middlewares/jwt.go
package middlewares
import (
"enterprise-api/app/models"
"enterprise-api/core"
"github.com/gin-gonic/gin"
)
func JWTAuth(role string) gin.HandlerFunc {
return func(c *gin.Context) {
signToken := c.Request.Header.Get("Authorization")
roleId, ok := c.Params.Get(role + "_id")
if signToken == "" || !ok { //未传递user_id
core.Error(c, 400, "无效的id")
c.Abort()
return
}
if role == "admin" || (role == "user" && core.ToInt(roleId) > 0) {
myclaims, err := models.VerifyToken(signToken)
if err != nil {
core.Error(c, 401, "token校验失败")
c.Abort()
return
}
//c.Set("userid", myclaims.Id)
if myclaims.Id == 0 || myclaims.Id != core.ToInt(roleId) {
core.Error(c, 401, "token校验失败")
c.Abort()
return
}
}
c.Next()
}
}
生成和校验token的方法
cat models/jwt.go
package models
import (
"enterprise-api/app/config"
"github.com/golang-jwt/jwt"
)
type MyCustomClaims struct {
Id int `json:"id"`
Username string `json:"username"`
jwt.StandardClaims
}
func CreateToken(claims MyCustomClaims) (string, error) {
//使用HS256加密方式
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signToken, err := token.SignedString([]byte(config.GetConfig().JWTKey))
if err != nil {
return "", err
}
return signToken, nil
}
func VerifyToken(signToken string) (*MyCustomClaims, error) {
var claims MyCustomClaims
token, err := jwt.ParseWithClaims(signToken, &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(config.GetConfig().JWTKey), nil
})
if token.Valid {
return &claims, nil
} else {
return nil, err
}
}
在登陆接口生成token
claims := models.MyCustomClaims{
Id: admin.Id,
Username: admin.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(), // 过期时间1星期
Issuer: admin.Username, // 签发人
},
}
token, err := models.CreateToken(claims)
在路由中使用
...
userRouter.Use(middlewares.JWTAuth("user"))
{
...
}