googleapis / google-auth-library-nodejs

🔑 Google Auth Library for Node.js
Apache License 2.0
1.71k stars 374 forks source link

How to use nodejs api of google auth in axios fetch? #1793

Closed startthecode closed 5 months ago

startthecode commented 5 months ago

How to use nodejs api of google auth in axios fetch using API URL directly on anchor tag is not safe and fetching this using axios is not working as expected

// react js fetch('http://localhost:5000/auth/google') .then(response => { // Handle response (e.g., redirect user to Google login page) }) .catch(error => { // Handle error });

Node js API export const authGoogle = asyncErrorHandler(async (req, res) => { // Redirect to Google's OAuth consent screen const url = googleAuthClient.generateAuthUrl({ access_type: "offline", scope: ["email", "profile"], redirect_uri: "http://localhost:5000/auth/google/callback", // Ensure this matches your actual callback URL }); res.redirect(url); });

export const googleCallback = asyncErrorHandler(async (req, res) => { const { code } = req.query; if (!code) { res.status(400).send("No authorization code"); return; }

try { const { tokens } = await googleAuthClient.getToken(code); // Set the credentials on the OAuth2 client. googleAuthClient.setCredentials(tokens);

// Retrieve user information
const userInfo = await googleAuthClient.verifyIdToken({
  idToken: tokens.id_token,
  audience:
    "xxxx",
});

console.info("User information retrieved:", userInfo.getPayload());
res.send(userInfo.getPayload());

} catch (error) { console.error("Error retrieving user info:", error); res.status(500).send("Error retrieving user info"); } });

danielbankhead commented 5 months ago

How to use nodejs api of google auth in axios fetch using API URL directly on anchor tag is not safe and fetching this using axios is not working as expected

I do not understand this question, perhaps these resources can be of assistance:

startthecode commented 5 months ago

Hi @danielbankhead, Suppose I log in to Google and get redirected to a callback URL where I update my user information in the database using Node. How will my front end know whether the login was successful? Should I call an API to check whether the user was created successfully?

My approach

  1. Upon receiving data on the callback route, the server will first update the database. Then, it will set an encrypted data cookie on the frontend using "res.cookie" and redirect to the frontend URL using "res.redirect(frontend)".
  2. The frontend will check if the URL contains something like "google auth success". If it does, the frontend will fetch an API that contains the cookie saved by the server to retrieve the data of the Google logged-in user.
  3. The server will verify the encrypted data that comes with the API request. If the encrypted data is verified, the server will return an auth token (with a maximum age of 15 days, which can also help to refresh the access token) and an access token (with a maximum age of 1 hour).

Many thanks Ashish

danielbankhead commented 5 months ago

Suppose I log in to Google and get redirected to a callback URL where I update my user information in the database using Node. How will my front end know whether the login was successful?

That would depend on your authorization model - if redirecting the successful response from the backend confirms a successful login.

To make this easier I would recommend the Google Identity Services JavaScript library for the frontend:

Further reading: