CORS issue with Google Oauth2 for server side webapps
Solution 1:
When you use the Authorization code grant (OAuth2 for backend apps - &response_type=code
), you must redirect the browser to the /auth
endpoint - you cannot use XHR for that. The user will be redirected back after authentication.
After redirecting to the /auth
endpoint, user needs to see in an address bar that the page is from Google (trusted source) and Google may need to do some more redirects in order to authenticate the user and present the consent page. So using XHR is not possible.
Update: For the third point, your backend API should return the HTTP 401 if the request doesn't contain valid credentials (not HTTP 30x redirect as it does now). Then, your Angular application needs an HTTP error handler which redirects the browser on HTTP 401 response.
But if you want to keep the token in your Angular application, it's better to use the Implicit grant, which is designed for applications running in a browser. Because using the Authorization code grant, your backend has the role of client (in OAuth2 scheme), but you want the Angular application to be the client (since it holds the token).