【发布时间】: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