我一直在使用服务器上的Passport进行用户身份验证.

现在我也想支持Facebook and Google login人.自从我开始使用Passport以来,我认为最好继续使用Passport策略,使用passport-facebookpassport-google-oauth.

我会提到Facebook,但这两种策略的行为是相同的.它们都需要重定向到服务器路由('/auth/facebook''/auth/facebook/callback').

在服务器上创建用户时,将创建JWT(不依赖从facebook\google收到的令牌).

     ... // Passport facebook startegy
     var newUser = new User();
     newUser.facebook = {};
     newUser.facebook.id = profile.id; 
     newUser.facebook.token = token; // token received from facebook
     newUser.facebook.name  = profile.displayName;   
     newUser.save(function(err) {
          if (err)
               throw err;
          // if successful, return the new user
          newUser.jwtoken = newUser.generateJwt(); // JWT CREATION!
          return done(null, newUser);
     });

问题是,在它创建之后,I don't find a proper way to send the JWT to the client,因为我也应该重定向到我的应用程序.

app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
        session: false,
        successRedirect : '/',
        failureRedirect : '/'
    }), (req, res) => {
        var token = req.user.jwtoken;
        res.json({token: token});
    });

代码高于redirects me to my app main page, but I don't get the token.

有什么解决办法吗?我的方法错了吗?任何建议都行.

推荐答案

我为这个问题找到的最佳解决方案是用一个包含JWT的cookie重定向到预期页面.

使用res.json只会发送json响应,不会重定向.这就是为什么这里的另一个建议答案不能解决我遇到的问题.

所以我的解决方案是:

app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
    session: false,
    successRedirect : '/',
    failureRedirect : '/'
}), (req, res) => {
    var token = req.user.jwtoken;
    res.cookie('auth', token); // Choose whatever name you'd like for that cookie, 
    res.redirect('http://localhost:3000'); // OR whatever page you want to redirect to with that cookie
});

重定向后,您可以安全地读取cookie并按预期使用JWT.(实际上,您可以在每次加载页面时读取cookie,以判断用户是否登录)

正如我之前提到的,可以将JWT作为查询参数重定向,但这非常不安全.

Mongodb相关问答推荐

如何将数组$拉到对象数组下

如何在Mongo中制作全覆盖索引

将子元素的数组值提取到 mongodb 中的单个数组中?

如何从集合中移除所有匹配的数组项?

数组过滤器 MongoDB

MongoDB 按 created_at 月聚合

分页时根据唯一字段mongodb获取数据

如何替换mongodb中的动态键?

_id 和 $oid 的区别; mongo 数据库中的 $date 和 IsoDate

如何在 MongoDb 中进行类似于嵌套 Sql Select 查询的嵌套查询

你如何在 Kubernetes 上设置 Mongo 副本集?

从命令行创建 MongoDB 用户

无法将 $match 运算符用于带有 ObjectId 的 mongodb/mongoose 聚合

C# mongodb driver 2.0 - 如何在批量操作中更新插入?

在MongoDB中查询一个半​​径内的位置

从 nodejs 到 mongodb 或 mongoose 的动态数据库连接

我在更新中对 $set 和 $inc 做错了什么

MongoDB 和 Robomongo: Can't connect (authentication)

如何使用户的邮箱在 mongoDB 中唯一?

有没有办法防止 MongoDB 向集合名称添加复数形式?