Redirect to previous page after authentication in node.js using passport.js file

I am trying to set up a login mechanism using node.js, express and passport.js. The login itself works very well, also the sessions are well saved with redis, but I have some problems redirecting the user to where he started from before being asked to authenticate.

eg. The user following the link http://localhost:3000/hidden is then redirected to http://localhost:3000/login , but then I want it to be redirected again to http://localhost:3000/hidden .

The purpose of this is that if a user accidentally gets a page that he must first register, he should be redirected to the / login site providing his credentials, and then redirected back to the site he previously tried to access.

Here is my login

 app.post('/login', function (req, res, next) { passport.authenticate('local', function (err, user, info) { if (err) { return next(err) } else if (!user) { console.log('message: ' + info.message); return res.redirect('/login') } else { req.logIn(user, function (err) { if (err) { return next(err); } return next(); // <-? Is this line right? }); } })(req, res, next); }); 

and here is my secureAuthenticated Method

 function ensureAuthenticated (req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login'); } 

which intercepts the /hidden page

 app.get('/hidden', ensureAuthenticated, function(req, res){ res.render('hidden', { title: 'hidden page' }); }); 

Html logout output is pretty simple

 <form method="post" action="/login"> <div id="username"> <label>Username:</label> <input type="text" value="bob" name="username"> </div> <div id="password"> <label>Password:</label> <input type="password" value="secret" name="password"> </div> <div id="info"></div> <div id="submit"> <input type="submit" value="submit"> </div> </form> 
+65
redirect authentication express
Nov 11
source share
7 answers

I don’t know about the passport, but here is how I do it:

I have middleware that I use with app.get('/account', auth.restrict, routes.account) that sets redirectTo in a session ... then I redirect / login

 auth.restrict = function(req, res, next){ if (!req.session.userid) { req.session.redirectTo = '/account'; res.redirect('/login'); } else { next(); } }; 

Then in routes.login.post I do the following:

 var redirectTo = req.session.redirectTo ? req.session.redirectTo : '/'; delete req.session.redirectTo; // is authenticated ? res.redirect(redirectTo); 
+55
Nov 11 '12 at 22:20
source share

In your ensureAuthenticated method ensureAuthenticated save the returned url in the session as follows:

 ... req.session.returnTo = req.path; res.redirect('/login'); ... 

Then you can update your passport. Verify the authenticity of the route with something like:

 app.get('/auth/google/return', passport.authenticate('google'), function(req, res) { res.redirect(req.session.returnTo || '/'); delete req.session.returnTo; }); 
+76
Jan 16 '14 at 0:16
source share

Take a look at connect-ensure-login , which works with your passport to do exactly what you want!

+12
Nov 14 '12 at 15:38
source share

If you use connect-ensure-login , this is a very simple and integrated way to do this with Passport using the successReturnToOrRedirect parameter. When used, the passport will send you back to the originally requested URL or return to the URL you specified.

 router.post('/login', passport.authenticate('local', { successReturnToOrRedirect: '/user/me', failureRedirect: '/user/login', failureFlash: true })); 

https://github.com/jaredhanson/connect-ensure-login#log-in-and-return-to

+5
Apr 19 '16 at 4:20
source share

My way of doing things:

 const isAuthenticated = (req, res, next) => { if (req.isAuthenticated()) { return next() } res.redirect( `/login?origin=${req.originalUrl}` ) }; 

GET / login controller :

 if( req.query.origin ) req.session.returnTo = req.query.origin else req.session.returnTo = req.header('Referer') res.render('account/login') 

POST / login controller :

  let returnTo = '/' if (req.session.returnTo) { returnTo = req.session.returnTo delete req.session.returnTo } res.redirect(returnTo); 

POST / logout controller (not sure if there is 100% ok, comments are welcome):

 req.logout(); res.redirect(req.header('Referer') || '/'); if (req.session.returnTo) { delete req.session.returnTo } 

Clear returnTo middleware (clears returnTo from the session on any route except auth routes - for me they are / login and / auth /: provider):

 String.prototype.startsWith = function(needle) { return(this.indexOf(needle) == 0) } app.use(function(req, res, next) { if ( !(req.path == '/login' || req.path.startsWith('/auth/')) && req.session.returnTo) { delete req.session.returnTo } next() }) 

This approach has two functions :

  • you can protect some routes with isAuthenticated middleware;
  • on any page, you can simply click on the login URL and after logging in to this page;
+2
Jul 19 '16 at 10:41
source share

There is an error in the answers of @chovy and @linuxdan without clearing session.returnTo if the user goes to another page after redirecting the login (this does not require authentication) and entering the system. So add this code to your implementations:

 // clear session.returnTo if user goes to another page after redirect to login app.use(function(req, res, next) { if (req.path != '/login' && req.session.returnTo) { delete req.session.returnTo } next() }) 

If you execute some ajax requests from the login page, you can also exclude them.




Another approach is to use flash in ensureAuthenticated

 req.flash('redirectTo', req.path) res.redirect('/login') 

And then in the GET login

 res.render('login', { redirectTo: req.flash('redirectTo') }) 

In the "Add hidden field" field, enter the login form (example in jade)

 if (redirectTo != '') input(type="hidden" name="redirectTo" value="#{redirectTo}") 

In the login field

 res.redirect(req.body.redirectTo || '/') 

Please note that redirectTo will be cleared after the first login with its name.

+1
Feb 20 '16 at 13:24
source share

The easiest (and correct) way to achieve this is to configure failureRedirect and successRedirect parameters .

+1
Jul 08 '16 at 14:11
source share



All Articles