|
@@ -1,6 +1,7 @@
|
|
|
package util
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
import (
|
|
|
|
|
+ "errors"
|
|
|
"fmt"
|
|
"fmt"
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
"net/http"
|
|
"net/http"
|
|
@@ -43,9 +44,15 @@ func GenerateToken(id int64, role string) (string, int64, error) {
|
|
|
func ValidateToken() gin.HandlerFunc {
|
|
func ValidateToken() gin.HandlerFunc {
|
|
|
return func(c *gin.Context) {
|
|
return func(c *gin.Context) {
|
|
|
// 获取请求中的token
|
|
// 获取请求中的token
|
|
|
- tokenString := c.GetHeader("Authorization")
|
|
|
|
|
|
|
+ tokenString, err := c.Cookie("token")
|
|
|
|
|
+ if err != nil {
|
|
|
|
|
+ c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "Authorization token is missing"})
|
|
|
|
|
+ c.Abort()
|
|
|
|
|
+ return
|
|
|
|
|
+ }
|
|
|
|
|
+ fmt.Println(tokenString)
|
|
|
if tokenString == "" {
|
|
if tokenString == "" {
|
|
|
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization token is missing"})
|
|
|
|
|
|
|
+ c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "Authorization token is missing"})
|
|
|
c.Abort()
|
|
c.Abort()
|
|
|
return
|
|
return
|
|
|
}
|
|
}
|
|
@@ -69,6 +76,21 @@ func ValidateToken() gin.HandlerFunc {
|
|
|
c.Next() // Token验证通过,继续执行后续处理
|
|
c.Next() // Token验证通过,继续执行后续处理
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
+func ValidateTokenToMyClaims(tokenString string) (*MyClaims, error) {
|
|
|
|
|
+ token, _ := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
|
+ return secretKey, nil
|
|
|
|
|
+ })
|
|
|
|
|
+ if token == nil || !token.Valid {
|
|
|
|
|
+
|
|
|
|
|
+ return nil, errors.New("Invalid token")
|
|
|
|
|
+ }
|
|
|
|
|
+ mc, ok := token.Claims.(*MyClaims)
|
|
|
|
|
+ if !ok {
|
|
|
|
|
+ return nil, errors.New("Invalid token")
|
|
|
|
|
+ }
|
|
|
|
|
+ return mc, nil
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
func ParseJWTWithValidation(tokenString string) (*MyClaims, error) {
|
|
func ParseJWTWithValidation(tokenString string) (*MyClaims, error) {
|
|
|
// 解析Token
|
|
// 解析Token
|
|
|
token, err := jwt.ParseWithClaims(tokenString, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
token, err := jwt.ParseWithClaims(tokenString, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|