【问题标题】:Why does Google authentication work locally but not on Heroku?为什么 Google 身份验证可以在本地工作,但不能在 Heroku 上工作?
【发布时间】:2021-05-10 19:05:04
【问题描述】:

Google 登录可以在我的本地计算机上运行,​​但在我部署到 Heroku 时却不行。我已经更新了我的 API 控制台以包含 heroku 主机。我在 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);
    }
  };

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

【问题讨论】:

    标签: node.js reactjs heroku web-applications google-signin


    【解决方案1】:

    我猜您希望用户登录以调用某些 Google 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);
        });
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2013-09-29
      • 2021-04-26
      • 2012-06-18
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      相关资源
      最近更新 更多