user11027821
user11027821

Reputation:

Handle JWT Verify Failure

I want to be able to change the JWT secret key and not cause a browser error for logged in users.

Currently, if a user is logged in and the JWT secret key is changed, their browser throws an error. This can only be fixed by the user manually deleting the cookies from their browser.

server.express.use((req, res, next) => {
  const { token } = req.cookies;
  if (token) {
    const { userId } = jwt.verify(token, process.env.APP_SECRET);
    req.userId = userId;
  }
  next();
});

What can I add to the above code so that if the jwt.verify fails, the user is forced to login again which would set a new cookie based on the new jwt secret key?

Upvotes: 1

Views: 13255

Answers (2)

Vishnu Pillai
Vishnu Pillai

Reputation: 11

You can use the call back to handle verify faliure and redirect if verify fails. You can use something like below


    jwt.verify(token, process.env.APP_SECRET, (err,userId) => {
                if(err)
          res.send({msg:"your_redirect_loaction_for_login_the_user_again"})
                } else {
                 // user verified
                 req.userId = userId
                }
            })

Upvotes: 1

Aurora
Aurora

Reputation: 136

instead of your if statement, use a try-catch block and send a res.status. If there will be a front end, on error, push the login-page again

try {
    const { userId } = jwt.verify(token, process.env.APP_SECRET);
    req.userId = userId;
    next()
} catch(err) {
  req.redirect("/login_page")
  res.status(400);
}

Upvotes: 8

Related Questions