我正在尝试用Node.js编写一个使用passport-facebook身份验证策略的web应用程序。默认情况下,示例中提供的机制的工作方式是将用户重定向到Facebook API,用户可以在其中输入用户名和密码进行登录。一旦Facebook验证了用户,它就会将令牌传递回应用程序中的一个回调URL。
现在,这些东西适用于我的应用程序。我可以使用Facebook登录,没有问题。但是,当我尝试登录时,我希望将一个额外的字段传递给服务器。
基本上,我的计划是在我的主页中添加一个TextField和一个Login Button。成功登录后,当回调函数执行时,我希望从该回调中捕获TextField的值。有没有办法做到这一点?任何帮助都是非常感谢的。
这是我的HTML页面的正文
<body>
<div class="container">
<div class="jumbotron text-center">
<p>Login or Register with:</p>
<a href="/auth/facebook" class="btn btn-primary"><span class="fa fa-facebook"></span> Facebook</a>
</div>
</div>
</body>这是我的nod.js代码:
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', passport.authenticate('facebook', {
successRedirect : '/dashboard',
failureRedirect : '/'
}));
app.get('/dashboard', isLoggedIn, function(req, res){
res.render('dashboard.ejs', {
user : {
name : req.user.facebook.name,
profilePic : req.user.facebook.profilePic
}
});
});基本上,我只想在我的LogIn按钮之前添加一个额外的TextField。从/dashboard路由中,我希望获得该TextField的值。因此,我的/dashboard代码将如下所示:
app.get('/dashboard', isLoggedIn, function(req, res){
res.render('dashboard.ejs', {
user : {
role: VALUE_FROM_TEXT_FIELD,
name : req.user.facebook.name,
profilePic : req.user.facebook.profilePic
}
});
});所以我有两个问题: 1.如何从前端传递这个TextField值。它应该在Form中还是什么? 2.如何在/dashboard路由中捕获TextField的值?
发布于 2016-06-21 16:37:48
您是否考虑过使用自定义回调而不是标准的Passport.js回调?
“本地”策略的一个例子是:
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});您应该能够在请求中传入附加值,并在回调中处理它。
编辑:对于您的特定场景,您可能会看到类似以下内容的内容...
app.get('/auth/facebook/callback', function (req, res, next) {
passport.authenticate('facebook', function (err, user, info) {
if (err) {
return next(err);
// let the next route handler do its thing...
// or you can handle the error yourself within this
// callback.
}
// if the user returns as nothing (doesn't exist) then redirect
if (!user) {
// this takes the place of failureRedirect
return res.redirect('/');
}
req.logIn(user, function (err) {
if (err) {
return next(err); // again - on error, 'next' depending on your requirement.
}
// this takes the place of successRedirect
return res.redirect('/dashboard');
});
})(req, res, next);
});希望这能澄清:)
发布于 2018-02-09 13:18:46
我所做的是传递一个自定义函数,而不是使用sucessRedirect,并将变量need传递给它。在我的示例中,它是req.session.backurl,它用于将它们发送回需要对其进行身份验证才能访问的页面。
users.get('/auth/facebook/callback',
//req.session.backURL||
passport.authenticate('facebook', { failureRedirect: '/login' }),function(req,res){
res.redirect(req.session.backURL||'/'); //custom function used instead of sucessRedirect
});https://stackoverflow.com/questions/37939044
复制相似问题