簡體   English   中英

為什么 Google 身份驗證在本地有效,但在 Heroku 上無效?

[英]Why does Google authentication work locally but not on Heroku?

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

有沒有人遇到過這個問題?

我猜您希望用戶登錄以調用某些 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);
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM