简体   繁体   中英

JWT doesn't validate the token received

I have a registrer endpoint and a login endpoint that response with a JWT

But when a receive this JWT this process throws 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

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:

 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. 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).

If you want to use asymmetric encryption (encrypt with private key; validate with public key) then another algorithm should be used (eg RS256). Example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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