【问题标题】:Token API and Backend Google OAuth in Node and AngularNode 和 Angular 中的令牌 API 和后端 Google OAuth
【发布时间】:2015-01-07 00:28:14
【问题描述】:

我们正在从使用状态(ExpressJS 会话)cookie 的 API 转换为无状态(令牌)API。

我们使用单一的 PassportJS 身份验证策略 (GoogleStrategy)。 OAuth 流程完成后,Google 会使用访问令牌回调后端路由。

以前,我们会在此时使用 req.session 设置一个 cookie,并将用户重定向到我们的仪表板。

使用令牌 API,当 Google 回调后端路由时,我们会根据电子邮件(充当用户名)和访问令牌(充当密码)生成令牌。

我们如何将此令牌传递给前端(Angularjs),以便它可以发出经过身份验证的请求?

我们是否需要切换到 Google 的前端 OAuth API?

【问题讨论】:

    标签: angularjs express oauth google-oauth passport.js


    【解决方案1】:

    将令牌传递给客户端 Web 应用程序的一种方法是将签名的 JSON Web 令牌放入 cookie 中,您的客户端应用程序可以访问和使用它(将令牌附加到每个 GET 请求或使用它在您的网络套接字身份验证中)。需要明确的是,您不再使用 cookie 作为服务器记录状态的参考,而是将它们用作客户端和服务器都可以访问的存储机制,您可以在其中存储编码的令牌。

    这是 generator-angular-fullstack 中的一个很好的例子:

    在路由器中,接收来自google认证的回调:

    .get('/callback', passport.authenticate('google', {
      failureRedirect: '/signup',
      session: false
     }), auth.setTokenCookie);
    

    还有setTokenCookie函数:

    function setTokenCookie(req, res) {
      if (!req.user) return res.json(404, { message: 'Something went wrong, please try again.'});
      var token = signToken(req.user._id, req.user.role);
      res.cookie('token', JSON.stringify(token));
      res.redirect('/');
    }
    

    还有signToken函数:

    function signToken(id) {
      return jwt.sign({ _id: id }, config.secrets.session, { expiresInMinutes: 60*5 });
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 2016-03-08
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2014-10-12
      • 2017-06-20
      相关资源
      最近更新 更多