Nodejs / Reactjs: Manipulating Token

Asked

Viewed 104 times

1

I’d like your help.

I have an API with Nodejs that performs user authentication (POST method), generating a Token (jwt) and returning the same:

module.exports = {
async authenticate(req, res) {
    const { email, password } = req.body;

    const response = await Person.findOne({ email }).select('+password');

    if (!response)
        return res.send({ error: 'User not found.'});

    if(!await bcrypt.compare(password, response.password))
        return res.send({ error: 'Invalid password.'});

    response.password = undefined;

    const token = jwt.sign({ id: response.id }, authConfig.secret, {
        expiresIn: 86400,
    });

    res.send({
        token,
    });
},
}

In my frontend (Reactjs), after the user click on the Login button, I have the following event:

handleSubimit = async e => {
    e.preventDefault();

    if (!this.canBeSubmitted()) { return; }

    if (this.state.email === '')
    {
        this.setState({
            erros: { email: "The 'Email' field is required." }
        });
        console.log(this.state.erros.email);
        return;
    };

    if (this.state.password === '')
    {
        this.setState({
            erros: { password: "The 'Password' field is required." }
        });
        console.log(this.state.erros.password);
        return;
    };

    const response = await api.post('/authenticate', {
        email: this.state.email,
        password: this.state.password,
    });

    if (response.data.error)
    {
        //do something here later
        return;
    }

    const token = response.data.token;

    api.defaults.headers.common['authorization'] = token;

    this.props.history.push('/main')
};

In this part of the code, I am sent the user data to the API to do the validations and return the Token, then I save the Token in the "headers" and redirect to the page "Main".

It turns out that on this page, I make some requests in the API, and for these requests, there is a "Middlewares" and it is not getting the value of the Token that was saved in the "headers".

module.exports = (req, res, next) => {
const authHeader = req.headers.authorization;

if(!authHeader)
    return res.status(401).send({ error: 'No token provided.' });

const parts = authHeader.split(' ');

if (!parts.length === 2)
    return res.status(401).send({ error: 'Token error.' });

const [ scheme, token ] = parts;

if (!/^Bearer$/i.test(scheme))
    return res.status(401).send({ error: 'Token malformatted.' });

jwt.verify(token, authConfig.secret, (err, decoded) => {
    if (err) return res.status(401).send({ error: 'Token invalid.' });

    req.userId = decoded.id;
    return next();
})
}

Someone can help?

Thanks in advance.

1 answer

0

Hello, it’s just a hunch looking over but look,

api.defaults.headers.common['authorization'] = token;

vc sets this on the front and soon after goes to another route, this setting is only valid in the api object that you used on that page when you changed page and imported the api object again it is already a new one without this setting. So your Middlewares won’t pick up the token because in the next requests there really isn’t a token, I suggest you store it in the browser’s storage and pass it when making the requests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.