所以我尝试使用express和passportjs将facebook身份验证添加到我的ionic2应用程序中。我几乎让它工作了,除了授权后将用户重定向回 ionic2 应用程序的最后一部分。我的两个应用程序都在不同的端口上运行; ionic2 运行于 http://localhost:8100以及在 http://localhost:8000 上运行的后端内容的 Express 应用程序
这些是我遵循的步骤:
- 在developers.facebook.com上创建应用并获取应用ID和 secret ID。
- 在“产品”>Facebook>“设置”下,我已将回调网址添加为
然后在我的在 localhost:8000 上运行的 Express 应用程序中,我添加了 facebook 身份验证策略,如 https://github.com/jaredhanson/passport-facebook 所示。是这样的:
passport.use(new FacebookStrategy({ clientID: FACEBOOK_APP_ID, clientSecret: FACEBOOK_APP_SECRET, callbackURL: "http://localhost:8000/auth/facebook/callback" }, function(accessToken, refreshToken, profile, cb) { User.findOrCreate({ facebookId: profile.id }, function (err, user) { return cb(err, user); }); } )); app.get('/auth/facebook', passport.authenticate('facebook')); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) { // Successful authentication, redirect home. res.redirect('/'); //how to redirect back to ionic app instead of / });
所以现在每当用户点击 ionic2 应用程序上的 facebook 按钮时,它都会进入 facebook 身份验证页面,一旦成功验证,它就会按预期重定向回 localhost:8000/auth/facebook/callback,但我想重定向回 ionic 应用程序。我怎么解决这个问题?需要一些指导来解决这个问题。
最佳答案
我不确定这是否是您所需要的,但我能够打开一个处理 Facebook 身份验证的新窗口。这是在我的提供程序中完成的:我的 successRedirect 如下所示:
public loginWithFacebook(callback : (data : any) => any){
this.callback = callback;
this.childWindow = this.nativeWindow.open(this.authEndpoint);
this.closeTimer = setInterval(() => {
if (this.childWindow.closed){
clearInterval(this.closeTimer);
this.childWindow = null;
this.closeTimer = null;
var passedJson = this.http.get(this.checkEndpoint).map(res => res.json());
passedJson.subscribe(data => {
this.callback(data);
});
}
}, 500);
}
这会检查窗口是否关闭。问题是我必须自动关闭它。我只是制作了一个成功重定向呈现的 html 页面,该页面关闭了创建的新窗口。这是我的 successRedirect
router.get('/api/auth/facebook/success', function (req, res) {
res.render('after-auth');
});
确保您的 Express 应用程序已在 app.js 中设置了 View 引擎。
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
你的views/after-auth.html应该是这样的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript">
window.close();
</script>
</body>
</html>
现在将关闭新窗口。我仍然遇到的唯一问题是,当我尝试进行下一个调用时, session 似乎没有保存。 req.user
对我来说似乎是未定义
关于node.js - 使用 ionic2 和 Express 应用程序进行 facebook-passport 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42220074/