React.js Passport Authentication unable to get req.user from client

Viewed 84

I am trying to authenticate a user through some API configured with passportjs. When I run the authentication request I get the redirect to the success route, but I can't get req.user. I tried through Postman and it works. I don't know what I'm forgetting. Could anyone help me?

This is my success route:

app.get("/success", async (req, res) => {
    if (req.user){
        return res.status(200).json({
            user: req.user,
            message: "Logged"
        });
    }
    else {
        return res.status(401).json({
            message: "User authentication failed"
        });
    }
});

This is my react code:

const handleSubmit = (e) => {
        e.preventDefault();
        fetch("http://127.0.0.1:3001/login", {
            method:"POST",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
            },
            redirect: "follow",
            body: JSON.stringify({email: email, password: password})
        }).then(resp => {
            return resp.json();
        }).then(data => console.log(data))
    }
1 Answers

While you are calling the success/ route you need to add the authorization header along with the fetch request. We need to add the Basic jwt | authentication token as the authorization key

const response = await fetch(apiURL, {
        method: 'GET',
        headers: {
            'Content-type': 'application/json',
            'Authorization': `Bearer ${token}`, 
            // add the basic jwt | drf token for Authorization Key
        },
        body: JSON.stringify(yourNewData)
    })
Related