[英]Why does Google authentication work locally but not on Heroku?
Google sign in works on my local machine but not when I deploy to Heroku. Google 登录在我的本地计算机上有效,但在我部署到 Heroku 时无效。 I have updated my API console to include the heroku host.
我更新了我的 API 控制台以包含 heroku 主机。 I'm using the free plan on Heroku.
我在 Heroku 上使用免费计划。 My sense is that the button click is not even registering on the API - I get no error or anything.
我的感觉是按钮点击甚至没有在 API 上注册 - 我没有收到任何错误或任何东西。
Client code:客户端代码:
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
href={
process.env.NODE_ENV === "production"
? `${window.location.origin}/api/google-sign-in`
: "http://localhost:5000/api/google-sign-in"
}
>
Google Sign In
</Button>
Server code:服务器代码:
googleSignIn = async (req: Request, res: Response, next: NextFunction) => {
console.log("Google sign in");
try {
const errors = {};
// Generate an OAuth URL and redirect there
const url = await this.oAuth2Client.generateAuthUrl({
scope: [
"profile",
"email",
"https://www.googleapis.com/auth/drive.file",
],
access_type: "offline",
});
// Get url
if (url) {
res.redirect(url);
} else {
res.redirect("/login");
}
} catch (e) {
next(e);
}
};
Has anyone encountered this issue before?有没有人遇到过这个问题?
I am guessing you want the user to login in order to call some Google APIs?我猜您希望用户登录以调用某些 Google API? If so you can omit the login part and use a Service account credential instead of an OAuth 2.0 Client ID.
如果是这样,您可以省略登录部分并使用服务帐户凭据而不是 OAuth 2.0 客户端 ID。 So you have a file called
auth.js
with所以你有一个名为
auth.js
的文件
const gal = require("google-auth-library");
const authFactory = new gal.GoogleAuth();
const SCOPES = ["https://www.googleapis.com/auth/drive"];
function authorize() {
return new Promise(resolve => {
const jwtClient = new gal.JWT(
process.env.GOOGLE_CLIENT_EMAIL,
null,
process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n"),
SCOPES
);
jwtClient.authorize(() => resolve(jwtClient));
});
}
module.exports = {
authorize
};
and you can do your job by calling it this way你可以这样称呼它来完成你的工作
require("dotenv").config();
const path = require("path");
var { google } = require("googleapis");
const googleAuth = require("./auth");
googleAuth
.authorize()
.then(auth => {
//call whatever Google API you wish, example drive to list files
})
.catch(err => {
console.log("auth error", err);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.