简体   繁体   English

JWT 不验证收到的令牌

[英]JWT doesn't validate the token received

I have a registrer endpoint and a login endpoint that response with a JWT我有一个注册端点和一个使用 JWT 响应的登录端点

But when a receive this JWT this process throws INVALID TOKEN但是当收到这个 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
}

邮差

I have read a lot of documentation but I cannot understand why the same token that I generate, then it is not recognized by the same App我已经阅读了很多文档,但我不明白为什么我生成了相同的令牌,然后它不被同一个应用程序识别

Thanks谢谢

Updated :更新 :

This is my Generate JWT code这是我的生成 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
}

I sign JWT in Go with this library: github.com/dgrijalva/jwt-go , and I checking it like this:我用这个库在 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)

I hope this help you.我希望这对你有帮助。

In this case the issue (as per the comments) was that an HS256 token was being produced using an RSA certificate as the secret.在这种情况下,问题(根据评论)是使用 RSA 证书作为机密生成 HS256 令牌。 The HSA256 algorithm is symmetric (see this question for more info) so to decode with this you need to pass in the same secret as used to create the token (in this case a certificate was being passed in as a key but the library was treating it as a []byte rather that processing the certificate). HSA256 算法是对称的(有关更多信息,请参阅此问题),因此要使用此算法进行解码,您需要传入与用于创建令牌相同的秘密(在这种情况下,证书作为密钥传入,但库正在处理它作为 [] 字节而不是处理证书)。

If you want to use asymmetric encryption (encrypt with private key; validate with public key) then another algorithm should be used (eg RS256).如果您想使用非对称加密(使用私钥加密;使用公钥验证),则应使用另一种算法(例如 RS256)。 Example . 例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM