Redirecting to previous page after authentication in node.js using passport.js

I'm trying to establish a login mechanism using node.js, express and passport.js. The Login itself works quite nice, also sessions are stored nicely with redis but I do have some troubles with redirecting the user to where he started from before being prompted to authenticate.

e.g. User follows link http://localhost:3000/hidden is then redirected to http://localhost:3000/login but then I want him to be redirected again back to http://localhost:3000/hidden.

The purpose of this is, if the user access randomly a page he needs to be logged in first, he shall be redirected to the /login site providing his credentials and then being redirected back to the site he previously tried to access.

Here is my login post

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 my ensureAuthenticated Method

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

which hooks into the /hidden page

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

The html output for the login site is quite 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>
98802 次浏览

我不知道护照怎么办,但我是这么办的:

我有一个与 app.get('/account', auth.restrict, routes.account)一起使用的中间件,它在会话中设置 redirectTo... 然后我重定向到/login

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

然后在 routes.login.post中我做以下事情:

var redirectTo = req.session.redirectTo || '/';
delete req.session.redirectTo;
// is authenticated ?
res.redirect(redirectTo);

看看 Connect-sure-login 连接-确保-登录,它与护照一起工作,可以做你想做的事情!

ensureAuthenticated方法中,将返回的 url 保存在会话中,如下所示:

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

然后你可以更新你的 Passport.enticate 路由,比如:

app.get('/auth/google/return', passport.authenticate('google'), function(req, res) {
res.redirect(req.session.returnTo || '/');
delete req.session.returnTo;
});

@ chovy 和@linuxdan 的回答有 bug,如果用户在登录重定向(不需要身份验证)后转到另一个页面并通过该页面登录,则不清除 session.returnTo。因此,将这些代码添加到它们的实现中:

// 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()
})

如果从登录页面执行一些 ajax 请求,也可以排除它们。


另一种方法是在 ensureAuthenticated中使用 闪念

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

然后在 GET 登录

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

在视图中添加隐藏字段到登录表单(例如翡翠)

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

在 POST 登录中

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

注意,在首次使用 redirectTo 登录后,redirectTo 将会清除。

如果您正在使用 Connect-sure-login 连接-确保-登录,那么有一个超级简单的、集成的方法,可以使用 successReturnToOrRedirect参数对 Passport 进行此操作。使用后,护照会将您发送回最初请求的 URL 或回退到您提供的 URL。

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

实现这一点的最简单(也是最恰当的)方法是 设置 ABC0和 successRedirect选项

我做事的方式:

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')

控制器:

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


res.redirect(returnTo);

POST/logout 控制器(不确定是否有100% OK,欢迎评论) :

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

Clear returTo 中间件 (从除 auth 路由之外的任何路由的 session 中清除 rereturn To ——对我来说,它们是/login 和/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()
})

这种方法有 two features:

  • 你可以用 已验证中间件保护一些路由;
  • 在任何页面 ,只需点击登录 URL,登录后 返回到该页面;