Node, Express REST authenticate with JWT token

Viewed 32

I am creating a blog using NodeJS and Express framework. To add extra security, I have separated the Sign Up & Login from the application. For this, I have created a REST API using Express in PORT 5000 (just for authentication of protected routes) and the actual application runs on 5001.

When user POSTS from the Login page in browser to ”http://www.example.com:5001” i.e., to my application. I authenticate the values from the REST API running on PORT 5000.

    //First user posts login data into my application
    router.post('/login', async (req, res) => {
      try{
        let payload = {
          'username': req.body.username,
          'password': req.body.password,
        }
        //sending the parameters for authentication to PORT 5000 (i.e., REST API)
        const response = await axios.post('http://www.example.com:5000/login', payload);
        if(response)
        {
          console.log(response.data);
          newToken = {
              token: response.data.token,
              refreshToken: response.data.refreshToken
            }
            res.redirect('/');
        }
      }
      catch(err){
        console.log(err);
      }
      
    })

The REST API responds after receiving the request.

app.post('/login', async (req, res, next) => {
try{
    let token, refreshToken;
    await connectDB();
    let result = await findOneUser(req);
    if(result)
    {
      //Initialize JWT Token Signature
        try {
          //Creating jwt token
          token = jwt.sign(
            { username: req.body.username },
            "secretkeyappearshere",
            { expiresIn: "1h" }
          );
          refreshToken = jwt.sign({ username: req.body.username },
            "some-secret-refresh-token-shit",
            { expiresIn: "3h" }
          );
          
        } catch (err) {
          console.log(err);
          const error = new Error("Error! Something went wrong.");
          return next(error);
        }
    }
    const response = {
      "status": "Logged in",
      "token": token,
      "refreshToken": refreshToken,
    }
    res.send(response);
    return next(false);
  }
  catch(err){
    console.log(err);
    tokenList[refreshToken] = response
    res.status(200).json(response);
    next(false);
  }
  });

Everything goes fine and I receive the token in my application.

But, problem starts when I resend the token. Suppose I have to authenticate a route (say) the settings route. I want users should again authenticate. So, I send back the token which I received during my first call to the REST API again, but now I don't receive anything back from the API to my application.

The first piece of code above has a variable called "newtoken", which I have set as global in my application.js file. I store the token that I received in the first call in this variable. Now, I use this to send another request to authenticate for the settings page/ route.

So, I again send this token in my next call like this

      router.get('/settings', async (req, res) => {
      let data = {
        params: {
            from: "2022-03-12",
            to: "2022-03-13"
        },
        headers: {
            "X-Auth-Token": newToken,
            "content-type": "application/json"
        }
      };
      try{
        const call = await axios.post('http://www.example.com:5000/validate', data);
        if(call){
          console.log(call.data);
          res.render('settings', { name: "Some test data" });
          }
        }
        catch(err)
        {
          console.log(err);
        }
    });

As, you can see I am resending the token data with headers. Actually, I have tried all others ways of sending, but nothings works. I do not get any response from my next call. ANy help would be highly appreciated. Thanks in advance.

1 Answers

Your router will handle many requests (from different users) in parallel, but your global variable newToken exists only once, this cannot work.

Your router could either send the token to the client (browser) in a session cookie, or use express-session and store the token in req.session.token:

// newToken = {
//   token: response.data.token,
//   refreshToken: response.data.refreshToken
// }
req.session.token = response.data.token;
req.session.refreshToken = response.data.refreshToken;
Related