0

I'm trying to use the Google Classroom API through my AWS EC2 web app (PHP-based), but I keep running into a CORS error.

I'm following this tutorial to try and request a new scope: https://developers.google.com/api-client-library/php/auth/web-app

When a user clicks a button, I make an AJAX request to my server to gather the required details and then call

$auth_url = $client->createAuthUrl();
header('Access-Control-Allow-Origin: *');
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL),false);

But I get the following error in my browser console

Failed to load https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=xxxx.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fexample.com%2Fsubdir%2Fpage%2Fajax%2Fconfirm_classroom_auth.php&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fclassroom.rosters.readonly&approval_prompt=auto&include_granted_scopes=true: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example.com' is therefore not allowed access. The response had HTTP status code 405.

I'm not really familiar with CORS beyond knowing what it is, so I would appreciate any suggestions on what I need to do to fix this.

BlackBelt2025
  • 441
  • 1
  • 7
  • 18
  • Have you tried setting the header before you run your `$client->createAuthUrl();` action? – Darren Jul 16 '18 at 02:35
  • Have you configured which domains to whitelist in the google api console for your oauth configuration? eg "_Accept requests from these HTTP referrers (web sites)_" – Scuzzy Jul 16 '18 at 03:10
  • @Darren I just tried that and nothing changed – BlackBelt2025 Jul 17 '18 at 01:33
  • @Scuzzy In the Google API Console, I had already set my website under "Authorized JavaScript origins" and "Authorized Redirect URIs" before I posted this question. Unless there is somewhere else I need to add that as well? – BlackBelt2025 Jul 17 '18 at 01:39
  • No that sounds like the correct place to have set them. Have you got both www and non-www versions, also local development domains if needed? – Scuzzy Jul 17 '18 at 05:24
  • Yeah, I added both http and https domains as well as www and non-www domains, but no joy... – BlackBelt2025 Jul 18 '18 at 01:28

1 Answers1

0

I'm not quite sure why using header() was causing an error, but I found a way around it.

Simply returning the authURL to my AJAX success function and then calling window.open(authURL) worked fine without a CORS error

BlackBelt2025
  • 441
  • 1
  • 7
  • 18