0

I have an API in which uses VerifyToken authentication with JWT. This works through postman, however it appears there's an issue passing this through to the frontend to ensure the token is verified.

For one, I have a code block to create verifyToken:

const verifyToken = (req, res, next) => {
  const authHeader = req.headers.token;
  if (authHeader) {
    const token = authHeader.split(" ")[1];
    jwt.verify(token, process.env.JWT_SEC, (err, user) => {
      if (err) res.status(403).json("Token is not valid!");
      req.user = user;
      next();
    });
  } else {
    return res.status(401).json("You are not authenticated!");
  }
};

If I run the following in Postman, it works all good, header and all. localhost:5000/api/users/updateUser/62a9be62a8262145b72feee9

This is then handled in requestMethods,

import axios from "axios";

const BASE_URL = "http://localhost:5000/api/";

const user = JSON.parse(localStorage.getItem("persist:root"))?.user;
const currentUser = user && JSON.parse(user).currentUser;
const TOKEN = currentUser?.accessToken;


export const publicRequest = axios.create({
  baseURL: BASE_URL,
});

export const userRequest = axios.create({
  baseURL: BASE_URL,
  bearer: { token: `Bearer ${TOKEN}` },
});

However when I pass this to the frotnend, for example through a request like this,

const updateUser = async () => {
  //include all in the state earlier with spread
  //update only position, which is input
  userRequest.put(`users/updateUser/${user._id}`, userData);
  console.log('your data has updated to', userData)
  //include the put request here for API
}

I am now getting an error for a 401: Error: Request failed with status code 401

It appears the token isn't being passed to the frontend correctly. What am I doing wrong?

n_d22
  • 413
  • 4
  • 12
  • Add Authorization to your axios instance like this https://stackoverflow.com/a/67486893/10728506 – Asad raza Aug 04 '22 at 12:42
  • 1
    Hi Raza, this does not appear to resolve the issue. Do you mean as such? export const userRequest = axios.create({ baseURL: BASE_URL, bearer: { token: `Bearer ${TOKEN}`, Authorization:`Bearer ${TOKEN}` }, }); – n_d22 Aug 04 '22 at 13:00

1 Answers1

0

Passing token in headers in Axios is not tuned correctly. Notice the headers config.

export const userRequest = axios.create({
  baseURL: BASE_URL,
  headers: { token: `Bearer ${TOKEN}` },
});

Another way to pass the token is where you are calling the API:

const updateUser = async () => {
  //include all in the state earlier with spread
  //update only position, which is input
  userRequest.put(`users/updateUser/${user._id}`, userData, {
    headers: {token: `Bearer ${TOKEN}`}
  });
  console.log('your data has updated to', userData)
  //include the put request here for API
}

Here is another tip: in your auth middleware by detecting a wrong token, do not go to next and return!

const verifyToken = (req, res, next) => {
  const authHeader = req.headers.token;
  if (authHeader) {
    const token = authHeader.split(' ')[1];
    jwt.verify(token, process.env.JWT_SEC, (err, user) => {
      if (err) {
        res.status(403).json('Token is not valid!');
        return;
      } else {
        req.user = user;
        next();
      }
    });
  } else {
    return res.status(401).json('You are not authenticated!');
  }
};
Raeisi
  • 1,647
  • 1
  • 6
  • 18
  • Hi Mr R, unfortunately it appears I still get error 403, which likely means there's somehting wrong with the assignment of the TOKEN in the chain – n_d22 Aug 04 '22 at 14:31
  • 403 error says the token is not valid. Please log your request headers and what you receive in the auth middleware as `token`. – Raeisi Aug 04 '22 at 14:41