Home > Back-end >  redirect with an error message using passport authenticate callback
redirect with an error message using passport authenticate callback

Time:10-20

I'm using passport with oauth2 strategy and am trying to find a way to pass along the error message to the error page which is a .ejs template file. Is there a way to pass on the actual error to this /error.ejs page ? If not is there a way to not redirect and just console log the error. I just need to see what the error is before it redirects ?

router.get(
  process.env.CALLBACK,
  passport.authenticate("oauth2", {
    failureRedirect: "/error",
    successRedirect: "/",
  })
);

router.get("/error", (req, res) => {
  console.log("req = ", req.error);
  res.render("error");
});

Nothing is coming back as far as error. I event tried message

CodePudding user response:

Based on the source code there are 2 approaches to this.

Method 1:

  • setting failureMessage: true in the authenticate params
  • getting the error message in the error path from req.session.messages
router.get(
  process.env.CALLBACK,
  passport.authenticate("oauth2", {
    failureRedirect: "/error",
    failureMessage: true,
    successRedirect: "/",
  })
);

router.get("/error", (req, res) => {
  console.log("req = ", req.session.messages);
  res.render("error");
});

(ref: https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js#L27)


Method 2:

  • instead of passing an object with params, you can supply a custom callback function:
router.get(
  process.env.CALLBACK,
  function (req, res, next) {
    passport.authenticate("oauth2", function (err, user, info, status) {
      if (err) {
        // do something with the error
        console.error("error: ", err);
      }
      // success
      res.redirect("/");
    })(req, res, next);
  }
);

(ref: https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js#L34)

  • Related