gpt4 book ai didi

go - JWT不验证收到的 token

转载 作者:行者123 更新时间:2023-12-01 22:26:00 26 4
gpt4 key购买 nike

我有一个注册端点和一个登录端点,它们使用JWT进行响应

但是当接收到此JWT时,此过程将抛出INVALID TOKEN

func ValidarToken(w http.ResponseWriter, r *http.Request) bool {

token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &models.Claim{}, func(token *jwt.Token) (interface{}, error){
return VerifyKey, nil
})

if err != nil {
switch err.(type) {
case *jwt.ValidationError:
vErr := err.(*jwt.ValidationError)
switch vErr.Errors {
case jwt.ValidationErrorExpired:
http.Error(w, "Su token ha expirado "+err.Error(),http.StatusUnauthorized)
case jwt.ValidationErrorSignatureInvalid:
http.Error(w, "La firma del token no coincide "+err.Error(),http.StatusUnauthorized)
default:
http.Error(w, "Su token no es válido "+err.Error(),http.StatusUnauthorized)
}
default:
http.Error(w, "Su token no es válido "+err.Error(),http.StatusUnauthorized)
}
return false
}

Postman

我已经阅读了很多文档,但是我无法理解为什么我生成相同的 token ,但同一应用程序无法识别它

谢谢

更新 :

这是我的生成JWT代码
func GeneroJWT(t models.Usuario) (string, error) {

leoClaves()

payload := jwt.MapClaims{
"email": t.Email,
"nombre": t.Nombre,
"apellidos": t.Apellidos,
"fecha_nacimiento": t.FechaNacimiento,
"biografia": t.Biografia,
"ubicacion": t.Ubicacion,
"sitioweb": t.SitioWeb,
"exp": time.Now().Add(time.Hour * 24).Unix(),
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)

tokenStr, err := token.SignedString(SignKey)

if err != nil {
return tokenStr, err
}
return tokenStr,nil
}

最佳答案

我使用以下库在Go中签署了JWT: github.com/dgrijalva/jwt-go ,我这样检查它:

		reqToken := r.Header.Get("Authorization")

splitToken := strings.Split(reqToken, "Bearer")
if len(splitToken) != 2 {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "No se ha proporcionado el token")
return
}

reqToken = strings.TrimSpace(splitToken[1])

claims := &Claims{}

tkn, err := jwt.ParseWithClaims(reqToken, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})

if err != nil {
if err == jwt.ErrSignatureInvalid {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "No autenticado")
return
}
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "No autenticado")
return
}
if !tkn.Valid {
w.WriteHeader(http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)


希望对您有所帮助。

关于go - JWT不验证收到的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59957579/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com