bradtraversy / proshop-v2

ProShop ecommerce website built with MERN & Redux Toolkit
532 stars 267 forks source link

Token and Cookie expiration not handled in client. #24

Closed bushblade closed 9 months ago

bushblade commented 9 months ago

The cookie and the JWT expire after 30 days. However for our private routing in the client our react app simply trusts that if we have a user in local storage, then that user is authenticated. So we have a situation where in the client they can access private routes, but the API calls to the server fail because there is no cookie with a valid JWT.

To reproduce the issue change backend/utils/generateToken.js to:

const generateToken = (res, userId) => {
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    // expiresIn: '30d',
    expiresIn: '60s',
  });

  // Set JWT as an HTTP-Only cookie
  res.cookie('jwt', token, {
    httpOnly: true,
    secure: process.env.NODE_ENV !== 'development', // Use secure cookies in production
    sameSite: 'strict', // Prevent CSRF attacks
    // maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
    maxAge: 60 * 1000, // 60 seconds
  });
};

So that the token and cookie expire after one minute. Then log in your user in the client and visit a private route such as /profile to see the users profile. Wait one minute and refresh the browser:

Screenshot_2023-10-07_10-34-45

This happens because we still have a user in LS but the JWT and cookie have expired.

bushblade commented 9 months ago

Closed in b8c171dd461a5fc18b3c2f84961feafc8ce6359e