简体   繁体   中英

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. I have updated my API console to include the heroku host. I'm using the free plan on Heroku. My sense is that the button click is not even registering on the API - I get no error or anything.

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? If so you can omit the login part and use a Service account credential instead of an OAuth 2.0 Client ID. So you have a file called auth.js with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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