Golang Gin 中使用 jwt

2020-10-18  本文已影响0人  TPEngineer
// 可以改成配置方式
var mySigningKey = []byte("AllYourBase")

// MyCustomClaims 定制
type MyCustomClaims struct {
    UserID uint `json:"user_id"`
    jwt.StandardClaims
}

// SignToken 签发 token
func SignToken(userID uint) (string, error) {

    // Create the Claims
    claims := &MyCustomClaims{
        userID,
        jwt.StandardClaims{
            ExpiresAt: time.Now().Add(time.Hour * 2).Unix(),
            Issuer:    "test",
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString(mySigningKey)
}

// ParseToken 解析 token
func ParseToken(tokenString string) (uint, error) {

    token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return mySigningKey, nil
    })

    if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
        fmt.Printf("%v %v", claims.UserID, claims.StandardClaims.ExpiresAt)
        return claims.UserID, nil
    }
    return 0, err

}

// JWTAuth 令牌验证,一般写成 gin 的中间件
func JWTAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        tokenString := c.Request.Header.Get("Authorization")
        if tokenString == "" {
            c.JSON(http.StatusUnauthorized, gin.H{
                "code": http.StatusUnauthorized,
                "msg":  "Authorization 不能为空",
            })
            c.Abort()
            return
        }
        _, err := utils.ParseToken(tokenString)

        if err != nil {
            c.JSON(http.StatusUnauthorized, gin.H{
                "code": http.StatusUnauthorized,
                "msg":  err.Error(),
            })
            c.Abort()
            return
        }

        c.Next()

        // after request

    }
}

// AdminAuth 角色权限验证,一般写成 gin 的中间件
func AdminAuth() gin.HandlerFunc {
    return func(c *gin.Context) {
        tokenString := c.Request.Header.Get("Authorization")
        if tokenString == "" {
            c.JSON(http.StatusUnauthorized, gin.H{
                "code": http.StatusUnauthorized,
                "msg":  "Authorization 不能为空",
            })
            c.Abort()
            return
        }
        userID, err := utils.ParseToken(tokenString)

        if err != nil {
            c.JSON(http.StatusUnauthorized, gin.H{
                "code": http.StatusUnauthorized,
                "msg":  err.Error(),
            })
            c.Abort()
            return
        }

        user, err := db.GetUserByID(userID)
        if err != nil {
            c.JSON(http.StatusUnauthorized, dto.Response{Message: err.Error()})
            c.Abort()
            return
        }
        if user.AccountType != "ADMIN" {
            c.JSON(http.StatusUnauthorized, dto.Response{Message: "权限不足"})
            c.Abort()
            return
        }
        c.Next()
    }
}


上一篇下一篇

猜你喜欢

热点阅读