【问题标题】:Handle Google OAuth with JWT (react + nodejs)使用 JWT (react + nodejs) 处理 Google OAuth
【发布时间】:2021-03-27 10:41:31
【问题描述】:

我正在开发 Web 应用程序的身份验证系统,使用 Next.js 作为客户端应用程序,使用 Node.js 作为 API。

  • 我的 Next.js 应用程序位于端口 3000
  • 我在端口 5000 上外部化了我的应用程序的 API

这就是我将 JWT 用于本地登录/注册策略的原因。 (我打算稍后将相同的 API 用于移动应用程序)

我现在想知道 Google 身份验证的最佳方法是什么。 我已经设置好了,但是不知道怎么把token给客户端。

流程如下:

  • 在登录页面(http://localhost:3000/signin),用户点击“谷歌认证”。它重定向到“http://localhost:5000/auth/google”
  • Passport 处理它,它重定向到 Google OAuth 页面。用户授权应用程序。
  • Google 重定向到回调 URL (http://localhost:5000/auth/google/redirect)

在回调路由中,我可以创建一个 JWT。但是我怎样才能把它还给客户呢? 我曾想过通过 URL 传递它,但我想知道它是否安全? 还有其他方法吗/我错过了重点吗?

router.get('/google/redirect', (req, res, next) => {
  return passport.authenticate('google', (err, user) => {
    if (err) {
      return res.redirect('http://localhost:3000/signin')
    }
    console.log(user)
    // Create JWT and redirect to http://localhost:3000/signin/oauth?token=xxx ?
  })(req, res, next)
})

如果需要,我可以显示更多代码,但它可以工作(代码不是阻塞点)。

提前谢谢你!

【问题讨论】:

  • Cookie 听起来像是一种选择。另一个是您的客户读取的隐藏输入。
  • @WiktorZychla 我的客户端应用程序 (Next.js) 和我的 api (node.js) 不共享相同的 URL。我无法从 API 创建 cookie 并从客户端访问它,这就是我使用 JWT 的原因。
  • 然后交叉发布令牌。

标签: node.js reactjs passport.js next.js google-authentication


【解决方案1】:

您所要做的就是设置 cookie 会话。当 google 发送对 /google/redirect 的响应时,passport.authenticate 将调用 req.login() 这将调用 serializeUser

  passport.serializeUser(
  (user, done ) => {
    done(null, user.id); // stores the id<4kb
  }
);

此函数将创建 passport:{user:userId}。这是关于用户的唯一识别信息。这是您需要会话的地方。因为passport.js 会自动查找req.session 并将passport 对象附加到req.session

由于我们只存储 userId,通常是 cookie-session 包。此包将设置 req.session 对象,passport.js 将附加 passport 对象,cookie-session 将其存储在客户端。

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 2022-07-19
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2017-11-25
    相关资源
    最近更新 更多