A especific endpoint from my API dosnt give me authorization. (must be BAD DEFINITION OF REQUEST)

52 Views Asked by At

I have several endpoints in my APIrest and a lot of them pass through the validations of the JWT token. When I try to update a user with my frontend app always tells me that i am not authorized. I tried to update the user with postman and everything works fine with it. postman result With the same Token i can do everything except update a user in my frontend app.

This is the request from my frontend app:

export function updateInfoApi(data){
    const url = `${API_HOST}/user`;
    const params = {
        method: "PUT",
        headers:{
            Authorization: `Bearer${getTokenApi()}`
        },
        body: data
    }
    return fetch(url, params)
    .then(response => {
        return response;
    }).catch(err => {
        return err;
    });
}

I have several requests in my frontend app with the same variables, and they work fine:

export function addTootApi(message){
    const url = `${API_HOST}/toots`
    const data = {
        message
    }
    const params ={
        method:"POST",
        headers:{
            "Content-Type":"application/json",
            Authorization: `Bearer${getTokenApi()}`
        },
        body: JSON.stringify(data),
    };
    return fetch(url, params).then(response => {
        if(response.status >=200 && response.status<300){
        return {code:response.status, message:"Toot enviado."}
        }
        return {code:500, message:"Error del servidor."}
    }).catch(err=> {return err;});
}

Here is where I process the token... but like i said this works fine cause always works... only donst work when i make the request to update user with my fronted app.

/*ProcessToken process the token*/
func ProcessToken(tk string) (*models.Claim, bool, string, error) {
    miClave := []byte("crazyforsnowboards")
    claims := &models.Claim{}

    splitToken := strings.Split(tk, "Bearer")
    if len(splitToken) != 2 {
        return claims, false, string(""), errors.New("Invalid format of token")
    }

    tk = strings.TrimSpace(splitToken[1])
    tkn, err := jwt.ParseWithClaims(tk, claims, func(token *jwt.Token) (interface{}, error) {
        return miClave, nil
    })
    if err == nil {
        _, found, _ := database.UserAlreadyExist(claims.Email)
        if found == true {
            Email = claims.Email
            UserID = claims.ID.Hex()
        }
        return claims, found, UserID, nil
    }
    if !tkn.Valid {
        return claims, false, string(""), errors.New("Invalid Token")
    }

    return claims, false, string(""), err
}

Thanks a lot guys!

1

There are 1 best solutions below

0
On

Never forget the JSON.stringify

Thanks alot guys for helping this sleepy guy :)