How to initiate OAuth2.0 flow?

How do I POST to Google’s OAuth 2.0 endpoints for authorization?

I’m building a chrome extension in React and have been following Google’s documentation. It seems pretty straightforward but I’m not fully grasping the mechanics of the implementation.

For example, in my popup.js file I call my background.js file which performs and axios POST request to the created redirect url. Step 3 in the guide says that Google will prompt the user for consent, however, that never happens. I get a 200 response but not sure where to go after that.

What am I doing wrong? Thank you!

  axios
      .post(
        `https://accounts.google.com/o/oauth2/v2/auth?
         scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
         include_granted_scopes=true&
         response_type=token&
         state=state_parameter_passthrough_value&
         redirect_uri=https%3A//oauth2.example.com/code& //actual values added 
         client_id=client_id //actual values added 
      )
      .then(function (response) {
        console.log('RESPONSE', response);
      });

>Solution :

Step 2 in that document is titled

Step 2: Redirect to Google’s OAuth 2.0 server

You are trying to do an XHR request with POST.

The document provides sample code both with and without their client library. Without the client library, you can see that it is a GET request using a form (which changes the URL in the browser, effectively redirecting):

/*
 * Create form to request access token from Google's OAuth 2.0 server.
 */
function oauthSignIn() {
  // Google's OAuth 2.0 endpoint for requesting an access token
  var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';

  // Create <form> element to submit parameters to OAuth 2.0 endpoint.
  var form = document.createElement('form');
  form.setAttribute('method', 'GET'); // Send as a GET request.
  form.setAttribute('action', oauth2Endpoint);

  // Parameters to pass to OAuth 2.0 endpoint.
  var params = {'client_id': 'YOUR_CLIENT_ID',
                'redirect_uri': 'YOUR_REDIRECT_URI',
                'response_type': 'token',
                'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
                'include_granted_scopes': 'true',
                'state': 'pass-through value'};

  // Add form parameters as hidden input values.
  for (var p in params) {
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('name', p);
    input.setAttribute('value', params[p]);
    form.appendChild(input);
  }

  // Add form to page and submit it to open the OAuth 2.0 endpoint.
  document.body.appendChild(form);
  form.submit();
}

Leave a Reply