0

I am trying to authenticate with google using a passport IN MERN app. Getting the below error but if I open the link available in below error in a new tab I am able authenticate with google.

Only issue is with below error

Error : Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email&client_id=1000813228585-k44nrfc0plt3kmupqu4rqcj0qcohhm35.apps.googleusercontent.com' (redirected from 'http://localhost:8000/auth/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CORS Config

app.use(cors({
  origin: ["http://localhost:3000"," https://accounts.google.com"],
        methods: "GET,POST,PUT,DELETE",
        credentials: true,
}));

Passport routes CLIENT_URL=http://localhost:3000

router.get("/google", passport.authenticate("google", ["profile"]));
router.get("/google/callback", passport.authenticate("google", {
    successRedirect: process.env.CLIENT_URL,
    failureRedirect: "/login/failed",
}));

router.get("/login/failed", (req, res) => {
    res.status(401).json({
        error: true,
        message: "Log in failure",
    });
});

Client req using Axios
REACT_APP_API_URL=http://localhost:8000

export const googleLoginReq = async () => {
  try {
    let res = await axios.get(`${REACT_APP_API_UR}/auth/google`, { withCredentials: true });
    return res.data;
  } catch (error) {
    console.log(error);
  }
};

Headers

General:

Request URL: https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email&client_id=1000813228585-k44nrfc0plt3kmupqu4rqcj0qcohhm35.apps.googleusercontent.com
Request Method: GET
Status Code: 200 
Referrer Policy: strict-origin-when-cross-origin

Response headers:

alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-encoding: gzip
content-security-policy: require-trusted-types-for 'script';report-uri /cspreport
content-security-policy: script-src 'report-sample' 'nonce-TOmywtPu0Qo8iQCEZhMnTw' 'unsafe-inline' 'unsafe-eval';object-src 'none';base-uri 'self';report-uri /cspreport
content-type: text/html; charset=utf-8
cross-origin-opener-policy-report-only: same-origin; report-to="coop_gse_qebhlk"
date: Wed, 25 Jan 2023 10:01:03 GMT
expires: Mon, 01 Jan 1990 00:00:00 GMT
p3p: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
pragma: no-cache
report-to: {"group":"coop_gse_qebhlk","max_age":2592000,"endpoints":[{"url":"https://csp.withgoogle.com/csp/report-to/gse_qebhlk"}]}
server: GSE
set-cookie: __Host-GAPS=1:WBh43ekzNFz-U7PJu6wrySL4P0fJVw:-8nse8F4eB1X5yrO;Path=/;Expires=Fri, 24-Jan-2025 10:01:02 GMT;Secure;HttpOnly;Priority=HIGH
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
x-frame-options: DENY
x-xss-protection: 1; mode=block

Request headers:

:authority: accounts.google.com
:method: GET
:path: /o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fauth%2Fgoogle%2Fcallback&scope=profile%20email&client_id=1000813228585-k44nrfc0plt3kmupqu4rqcj0qcohhm35.apps.googleusercontent.com
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-IN,en-US;q=0.9,en;q=0.8
cookie: __Secure-3PAPISID=0fADWvGybtHw6h4E/AuZfyvMRCsCGQG4m9; __Secure-3PSID=TAgcETHlEPmlnVokgxJP67RdvdDCwLo6zS5s8W_yA_tnNn79ks2clkRgFmsvP0yZRult_A.; __Host-3PLSID=o.chat-dl.google.com|o.chat.google.com|o.console.cloud.google.com|o.drive.google.com|o.mail.google.com|o.meet.google.com|o.myaccount.google.com|s.IN|s.youtube:TAgcET_mZKiKd0P8KBaXK00vnWmuYQPOt8sRxUc75wk7hbKaEbtuam5S-oCMNPtkvpnT_w.; NID=511=ui5rQ6D8-KrHAUOn491ZvzQP7VdaQ-r94ktEYHfqHSWwWXK9E29AWZYBZMZRE8g9Zesepsp6c6lp-VjKU1dUWus4ICU9FkArFbf7bw5E6wQFcb9mOasQA0yV1qPgVErv49i1GLrgpHc373TwTqgC1Oah1nme4oaN2VBBN-r5YyAXun1eL4P-u3Iw7W6SV7ExIqnkunp4bQoG9ThcP5DjlkyDy14sK_YuV5EZwGIm9P6a18SsDcHDE2quUps7_LdjcE_CRL_OcB8v53R-Y9msRdxrBNGhY23yvgFbVkANBh5wKElpTvfTG7vxrDxZW_8Ol3LcM_wmKdD1ePuPHQrh4v1wQ29i16Vd0Z7obEEfP2hdig; LSOLH=AH+1Ng3ry+24BKCDnw1k/j8gBn5vXNTEUY4wwBo52xPp9smoYZt/jdHVLmQLmcStBp6zxduzEbOG; 1P_JAR=2023-01-25-10; __Secure-3PSIDCC=AIKkIs3zFB8Qc0Oo3-AzH4hzyJkZFsjp0ZEMsrezMMUBxtGeayEzfxjxwSaygz9LHj3OTAhrEdFL
origin: null
referer: http://localhost:3000/
sec-ch-ua: "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36

google api credentials urls enter image description here

1 Answers1

0

CORS can be a bit fiddly to setup, and errors like this are pretty common. There is a good CORS primer available here.

What is happening in the background is that the API is taking the contents of the origin header, and trying to match it with what is enabled in the credential URLs.

However, if you look at the request headers that are sent, the origin is set as null, which isn't matching your list. Adding null to your configuration should get things working.

Nota bene: it looks like this is a work around for a dev environment, make a note to back it out when you get to prod ;)

Buffoonism
  • 1,669
  • 11
  • 11
  • still not working if add like this ``` origin:["http://localhost:3000","null"], ``` if add only ``` origin:"null" ``` then my client is not able to find server and getting below error Access to XMLHttpRequest at 'http://localhost:8000/api/customize' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. – Deepanshu Gupta Jan 27 '23 at 15:56
  • Ok, more detail needed! You mentioned axios as the client, but the error and headers appear to be from a browser: is this a react SPA, running in a browser? – Buffoonism Jan 27 '23 at 16:57
  • Basically, there is a button in the front end created using Reactjs. Once the button is clicked it will call an API HTTP://localhost:8000/auth/google from the origin HTTP://localhost:3000 In the backend, a authenticate middleware is called. which redirects from HTTP://localhost:8000 to https://accounts.google.com Through which google authentication will be done and it return with profile. After that it comes to callback function /auth/google/callback at this route. – Deepanshu Gupta Jan 28 '23 at 03:43
  • Ensure CORS response header values are valid A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request . To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values. Note that if an opaque response is sufficient, the request's mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque). – Deepanshu Gupta Jan 28 '23 at 04:53
  • Is the question a duplicate of this one? https://stackoverflow.com/questions/45975135/access-control-origin-header-error-using-axios – Buffoonism Jan 28 '23 at 07:58
  • No, my requirement is a bit different. What I am trying to do is call a google API from my server which is redirected from my frontend. HTTP://localhost:3000 > HTTP://localhost:8000 > https://accounts.google.com > HTTP://localhost:8000 > HTTP://localhost:3000 like this my cycle is working but when 8000 to google it goes cors blocked that. So when my API endpoint is called it gone to google authenticate middleware so I can't add res.header in that middleware. – Deepanshu Gupta Jan 29 '23 at 04:54