Codojojo
Codojojo

Reputation: 101

httpOnly Cookies vs Authorization headers for passing JWT

so I'm kind of confused about the correct way to pass JWT authorization, I know a common approach is that you can use a Authorization header to verify it, something like this:

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

However, if I used cookie to store my JWT token after I login such as:

res.cookie("accessToken", accessToken, { httpOnly: true });
res.cookie("refreshToken", refreshToken, { httpOnly: true });

Does that mean I can ignore the authHeader above and use directly from the cookie to verify my Token? Something like:

const verifyToken = (req, res, next) => {
  //USING TOKEN FROM COOKIES
  const accessToken = req.cookies.accessToken;
  const refreshToken = req.cookies.refreshToken;
  if (accessToken && refreshToken) {
    jwt.verify(accessToken, process.env.JWT_KEY, (err, user) => {
      if (err) {
        res.status(403).json("Token is not valid!");
      }
      req.user = user;
      next();
    });
  } else {
    res.status(401).json("You're not authenticated");
  }
};

Thanks for any clarification

Upvotes: 6

Views: 3385

Answers (1)

Tore Nestenius
Tore Nestenius

Reputation: 19921

I think it is a bad practice to store the tokens as cookies directly, as anyone accessing the computer can access them. The cookies are not protected when they are stored in the browser.

Just setting HttpOnly is also a bad practice, you should also set the Secure and SameSite attribute on the cookies as well to make them more secure. Even better encrypting them before you store them inside the cookie.

A better approach can be to look at the BFF pattern as described here

To complement this answer, I wrote a blog post that goes into more detail about this topic: Debugging cookie problems

Upvotes: 2

Related Questions