Google OAuth2: Redirect has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect

你离开我真会死。 提交于 2020-01-24 09:34:07

问题


Trying to implement Google OAuth2 and using https://github.com/google/google-api-nodejs-client#authorizing-and-authenticating as reference. When redirecting user to consent page like this

var url = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: some_scope
    });
 res.redirect(url);

I get this error in browser console (links edited):

XMLHttpRequest cannot load localhost:8080/myPageName. Redirect from localhost:8080/myPageName to accounts.google.com/o/oauth2/auth?access_type=... has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

The strange thing is that I am getting this error only when executing the flow from GUI (user presses the button; angular2 front-end). When I put localhost:8080/myPageName directly into the browser address bar everything works fine (get consent form and then tokens).

Any help is appreciated. Thank you.


回答1:


I had the same issue (with a react frontend, but it's the same). This is probably because from the server you use redirect, which triggers CORS (even if from your server you allow it).

you have to return the redirect URL to your front-end in some other way, capture it from the front-end app and then call the URL you need to invoke.




回答2:


A simple solution is create a hidden link with the required query parameters and click the link using JavaScript, if google supports HTTP POST submission then a hidden form can be created and submitted directly again using JavaScript magic to bypass the CORS restriction which I guess is either already removed or will be removed in near future.



来源:https://stackoverflow.com/questions/41703169/google-oauth2-redirect-has-been-blocked-by-cors-policy-request-requires-prefli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!