繁体   English   中英

为什么我的 OAuth2 身份验证在 heroku 上出现 redirect_uri_mismatch 错误?

[英]Why am I getting redirect_uri_mismatch error on heroku with my OAuth2 authentication?

我在我的一个应用程序中使用 google plus API。 它在我的本地存储库中运行良好,但在 Heroku 上,它抛出此错误:错误:redirect_uri_mismatch

请求中的重定向 URI http://discuss-my-anime.herokuapp.com/auth/google/redirect与为 OAuth 客户端授权的不匹配。

我的 google plus API 凭证如下: Google plus API 凭证

我正在使用护照包进行身份验证,我的护照设置代码如下:

 const passport = require("passport"); const GoogleStrategy = require("passport-google-oauth20"); const keys = require("./keys"); const User = require("../models/user-model"); passport.serializeUser((user, done)=>{ done(null, user.id); }); passport.deserializeUser((id, done)=>{ User.findById(id).then((user)=>{ done(null, user); }); }); passport.use( new GoogleStrategy({ //options for google strategy callbackURL: "/auth/google/redirect", clientID: keys.google.clientID, clientSecret: keys.google.clientSecret }, (accessToken, refreshToken, profile, done)=>{ //check if user already exists User.findOne({googleId: profile.id}).then((currentUser)=>{ if(currentUser){ //already have a user console.log("user is: " + currentUser); done(null, currentUser); } else{ //creating new user new User({ username: profile.displayName, googleId: profile.id, thumbnail: profile._json.picture }).save().then((newUser)=>{ console.log("new user created: " + newUser); done(null, newUser); }); } }); }) );

您收到此错误的原因是在此处使用相对路径:

callbackURL: "/auth/google/redirect"

由于 dev 和 prod 环境 url 不同,我们使用相对路径。 最终,googleStrategy 会弄清楚要放在此处的域。 这就是我们得到不匹配网址的地方。 在开发环境中,它附加在正确的域上,但在生产环境中却做错了。

为了确保来自我们浏览器的流量被路由到正确的服务器,Heroku 使用代理或负载均衡器。 googleStrategy 在生产中错误地计算该域的原因是,默认情况下,该策略假定如果我们来自浏览器的请求曾经通过任何类型的代理,那么该请求不应再是 https,因为它本质上不想信任通过代理发出的请求。 在我们的例子中,我们完全信任 heroku 代理,就像我们的应用程序托管在 heroku 上一样。

如果您将以下属性放在 GoogleStrategy 初始配置对象中

proxy: true 

这对 GoogleStrategy 说,如果我们的请求通过任何代理运行,您可以信任它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM