|
|
|
@ -3,9 +3,12 @@ package utils |
|
|
|
import ( |
|
|
|
"appNewPlatform/appConstant" |
|
|
|
"appNewPlatform/generalmethod" |
|
|
|
"appNewPlatform/utils/formatoutput" |
|
|
|
"fmt" |
|
|
|
"strconv" |
|
|
|
"time" |
|
|
|
|
|
|
|
"github.com/gin-gonic/gin" |
|
|
|
"github.com/golang-jwt/jwt" |
|
|
|
) |
|
|
|
|
|
|
|
@ -60,7 +63,9 @@ func ReleaseToken(userKey string) (token string, err error) { |
|
|
|
|
|
|
|
@ 返回值 |
|
|
|
|
|
|
|
# |
|
|
|
#jwt.Token |
|
|
|
#jwt.Token |
|
|
|
#error |
|
|
|
|
|
|
|
@ 方法原型 |
|
|
|
|
|
|
|
@ -73,3 +78,78 @@ func ParseToken(tokenString string) (*jwt.Token, *Claims, error) { |
|
|
|
}) |
|
|
|
return token, claims, err |
|
|
|
} |
|
|
|
|
|
|
|
/* |
|
|
|
* |
|
|
|
@ 作者: 秦东 |
|
|
|
@ 时间: 2025-02-13 10:44:02 |
|
|
|
@ 功能: 验证jwt令牌 |
|
|
|
@ 参数 |
|
|
|
|
|
|
|
#tokenString 令牌 |
|
|
|
|
|
|
|
@ 返回值 |
|
|
|
|
|
|
|
#Claims 解析后数据 |
|
|
|
#error 信息 |
|
|
|
|
|
|
|
@ 方法原型 |
|
|
|
|
|
|
|
# |
|
|
|
*/ |
|
|
|
func ValidateToken(tokenString string) (*Claims, error) { |
|
|
|
token, claims, err := ParseToken(tokenString) |
|
|
|
if err != nil { |
|
|
|
return nil, err |
|
|
|
} |
|
|
|
if !token.Valid { |
|
|
|
return nil, fmt.Errorf("无效的令牌") |
|
|
|
} |
|
|
|
if time.Now().Unix() > claims.ExpiresAt { |
|
|
|
return nil, fmt.Errorf("令牌已过期") |
|
|
|
} |
|
|
|
return claims, nil |
|
|
|
} |
|
|
|
|
|
|
|
/* |
|
|
|
* |
|
|
|
@ 作者: 秦东 |
|
|
|
@ 时间: 2025-02-13 11:36:59 |
|
|
|
@ 功能: |
|
|
|
@ 参数 |
|
|
|
|
|
|
|
# |
|
|
|
|
|
|
|
@ 返回值 |
|
|
|
|
|
|
|
# |
|
|
|
|
|
|
|
@ 方法原型 |
|
|
|
|
|
|
|
# |
|
|
|
*/ |
|
|
|
func AuthMiddleware() gin.HandlerFunc { |
|
|
|
return func(c *gin.Context) { |
|
|
|
tokenString := c.GetHeader("Authorization") |
|
|
|
if tokenString == "" { |
|
|
|
formatoutput.Result(300, tokenString, c, "未获得授权!") |
|
|
|
c.Abort() |
|
|
|
return |
|
|
|
} |
|
|
|
if len(tokenString) > 7 && tokenString[:7] == "Bearer " { |
|
|
|
tokenString = tokenString[7:] |
|
|
|
} else { |
|
|
|
formatoutput.Result(300, tokenString, c, "授权标头无效!") |
|
|
|
c.Abort() |
|
|
|
return |
|
|
|
} |
|
|
|
_, claims, err := ParseToken(tokenString) |
|
|
|
if err != nil { |
|
|
|
formatoutput.Result(300, tokenString, c, "无效的令牌!") |
|
|
|
c.Abort() |
|
|
|
return |
|
|
|
} |
|
|
|
c.Set("username", claims.UserId) |
|
|
|
c.Next() |
|
|
|
} |
|
|
|
} |
|
|
|
|