[英]Node.js + Passport - Unexpected redirect when using Google oauth2
I am building a node.js server using passport middleware.我正在使用护照中间件构建 node.js 服务器。 I'm trying to authenticate my users via Google's oauth2.
我正在尝试通过 Google 的 oauth2 对我的用户进行身份验证。
The authentication process is as follows:认证过程如下:
User is redirected to <server>/auth/google
, which uses passport's middleware thus: passport.authenticate("google", { scope: ["profile", "email"] })
用户被重定向到
<server>/auth/google
,它使用了护照的中间件: passport.authenticate("google", { scope: ["profile", "email"] })
The user then receives Google's login page and logins然后用户会收到 Google 的登录页面并登录
Google then redirects user to <server>/auth/google/callback
, which uses passport's middleware thus: passport.authenticate("google", { failureRedirect: "/", session: false })
然后谷歌将用户重定向到
<server>/auth/google/callback
,它使用了护照的中间件: passport.authenticate("google", { failureRedirect: "/", session: false })
In the end, the user is redirected to <client>?token=<token>
最后,用户被重定向到
<client>?token=<token>
I am hosting my project's front-end on Netlify and the back-end on NOW.我在 Netlify 上托管我的项目前端,而在 NOW 上托管后端。
Everything works fine when running on localhost, yet when running in production there is an unexpected redirect during step 3, in which the user is redirected to <server>/auth/google/t?token=<long-token-string>
instead of the path mentioned.在 localhost 上运行时一切正常,但在生产中运行时,在第 3 步中出现意外重定向,其中用户被重定向到
<server>/auth/google/t?token=<long-token-string>
而不是提到的路径。
What is the reason behind this redirect?这种重定向背后的原因是什么? Any suggestions?
有什么建议么?
Thanks,谢谢,
Ofek奥菲克
After reading and debugging passport.js
and oauth
, I finally found out what was wrong.在阅读和调试
passport.js
和oauth
,我终于发现了问题所在。 This was a bug in my code.这是我的代码中的一个错误。
I used this in my config file:我在我的配置文件中使用了这个:
export const CLIENT_ORIGIN =
process.env.NODE_ENV === "production"
? "https://<project-name>.netlify.com"
: ["http://127.0.0.1:3000", "http://localhost:3000"];
So, when running on localhost, setting callbackURL = CLIENT_ORIGIN[1]
in the StrategyOptions made sense, but when running in production CLIENT_ORIGIN
received the value "https://<project-name>.netlify.com"
(a string instead of an array), therefore CLIENT_ORIGIN[1]
returned the character "t"
.因此,在 localhost 上运行时,在 StrategyOptions 中设置
callbackURL = CLIENT_ORIGIN[1]
是有意义的,但在生产环境中运行时CLIENT_ORIGIN
收到值"https://<project-name>.netlify.com"
(字符串而不是数组),因此CLIENT_ORIGIN[1]
返回字符"t"
。 As a result, the callbackURL
received the value "t"
, which caused this unpredicted (and undocumented) redirect.结果,
callbackURL
收到了值"t"
,这导致了这个不可预测的(和未记录的)重定向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.