Question

Front end is 100% JS. User click on sign in button and an authResult['code'] is received and send via ajax to localhost/api/user/login which has the following content:

     $code = $data['code'];
    require_once 'Google/Client.php';
    $client = new Google_Client();
    $client->setClientId('xxxxxx');
    $client->setClientSecret('xxxxx');
    $client->setRedirectUri('http://localhost:8080');
    $client->setScopes('email'); //Why do I need this? I already set scope in JS.
    $client->authenticate($code);   //It fails here. with no error. just 400 bad request.
    $token = json_decode($client->getAccessToken());
    $reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
          $token->access_token;
    $req = new Google_HttpRequest($reqUrl);
    $tokenInfo = json_decode(
      $client::getIo()->authenticatedRequest($req)->getResponseBody());

   //Check errors. 
   //Save user personal info in database
   //Set login sessions
  1. Why do I need to set scopes if I already set them in javascript?
  2. Why is it failing when authenticate function is called? Im getting no erros.
  3. Why do I need a setRedirectUri() when it is on the backend?
Was it helpful?

Solution

  1. You don't need to set scopes in this case.
  2. (see answer 3, but also): Check your client ID matches the one used in the Javascript, and that the client secret is exactly as in the console (no trailing/leading spaces).
  3. Changing your redirecturi to 'postmessage' - this is the string used when the code was generated via the Javascript process.

You can also try manually constructing the URL and calling it with curl to make sure everything is as you expect: https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top