为什么谷歌认证工作在本地,而不是在Heroku?



Google sign in在我的本地机器上工作,但当我部署到Heroku时不起作用。我已经更新了我的API控制台,以包含heroku主机。我在赫罗库用的是免费套餐。我的感觉是,按钮点击甚至没有在API上注册-我没有得到任何错误或任何东西。

客户机代码:

<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>

服务器代码:

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);
}
};

以前有人遇到过这个问题吗?

我猜你想让用户登录,以调用一些谷歌api ?如果是这样,您可以省略登录部分,并使用服务帐户凭据而不是OAuth 2.0客户端ID。我们有一个名为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
};

你可以这样调用它

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);
});

最新更新