我是护照的新手,我正在尝试将用户重定向到他们之前使用Facebook验证的页面。我试图在会话中设置“req.session.returnTo”属性,但它在facebook / auth回调中不断被删除(该函数中的任何地方都显示为未定义)。我的方法出了什么问题?
受保护的路线:
app.post('/api/recipebox', ensureAuthenticated, function (req, res) {
});
ensureAuthenticated:
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
req.session.returnTo = req.path;
res.redirect('/#!/login');
}
// Facebook / Passport.js回调:
app.get('/auth/facebook/callback', function (req, res, next) {
passport.authenticate('facebook', function (err, user, redirectURL) {
// console.log(' in the callback ');
if (err) {
console.log(err);
return res.redirect('/#!/login');
}
if (!user) {
return res.redirect('/#!/signup');
}
if (req.user) {
// console.log("==================== This is the user from routes.js", req.user);
res.cookie('user', JSON.stringify(user));
}
//actually storing the fact that they are logged in:
req.login(user, function (err) {
if (err) {
return res.redirect('/#!/login');
}
// console.log('=========== here!', user);
res.redirect(req.session.returnTo || '/#!');
req.session.returnTo = null;
});
})(req, res, next);
})
答案 0 :(得分:0)
我正在使用本地策略进行电子邮件和密码登录。我参考了以下链接来设置我的护照JS身份验证和登录:Passport Facebook
使用如下所示的路由
app.get('/auth/facebook/callback',passport.authenticate('facebook',
successRedirect: 'whatever-url-you-want',
failureRedirect: '/login' }));
答案 1 :(得分:0)
我最终在客户端上执行此操作:
$httpProvider.interceptors.push(function ($q) {
return {
request: function (request) {
// console.log("hello");
// console.log(window.location.href);
request.headers.lastUrl = window.location.href;
return request;
},
responseError: function (response) {
return $q.reject(response);
}
};
});
并在服务器上:
app.use(function (req, res, next) {
//req.session.returnTo is available everywhere in router now.
//filter if it not auth/login/signup, then save it. only update return to when it's not one of those.
if (req.get('lastUrl') !== undefined) {
var lastUrl = req.get('lastUrl');
if (lastUrl.indexOf("login") === -1 && lastUrl.indexOf("signup") === -1 && lastUrl !== "http://localhost:3000/#!/") {
req.session.returnTo = lastUrl;
}
console.log(req.session);
}
next();
});
希望它能帮助别人。我没有成功运行successRedirect,如果你最终在登录/注册/一起从页面中删除,我认为不会那么简单。