Categories
Uncategorized

How to redirect passport to referrer after authentication

PassortJSPassportJS by default redirects to the homepage and not the referrer, after authentication. To achieve redirection to the referrer without installing any additional plugins, all that needs to be done is to store the referrer URL in session.redirectTo variable. This can be used to later redirect the user once the authentication is performed successfully. It does not matter whether the session is stored locally or remotely (scalable applications).

Storing the referrer URL

app.use(function (req, res, next) {
    if (req.user) {
        next();
    } else {
        session.redirectTo = req.url;

       // or   session.redirectTo = req.originalUrl;
       // if that doesn't work try this
       //     require('url').parse(req.url).path;

      res.redirect('/login');
    }
});

Redirecting to required URL after successful login

// For 0Auth 2.0 Passport Strategy

app.get('/auth/provider/callback',
 passport.authenticate('provider',
  { failureRedirect: '/login' }, 
  function(req, res) {
    // You can log the user to backend API logs and then upon success        
    //redirect to referrer
   
   if (session.redirectTo)
      res.redirect(session.redirectTo);
   else 
      res.redirect('/');
 }
));