Google API: Invalid grant_type when trying to get access token

3.8k Views Asked by At

I have following JS code to get the authentication code for the OAuth2 flow with Google:

        gapi.client.init({
          apiKey: apiKey,
          clientId: clientId,
          scope: scopes
        });

//...

        gapi.auth2.getAuthInstance().grantOfflineAccess({
              scope: 'email profile'
            })
            .then(function(response) {
              if (response && !response.error) {
                // google authentication succeed, now post data to server.
                $.ajax({
                  type: 'POST',
                  url: "my_url",
                  data:  {
                    code: response.code
                  },
                  success: function(data) {
                       //...
                  },
                  error: function(er) {
                    console.log(er);
                  }
                });
              } else {
                console.log('google authentication failed');
                console.log(response)
              }
            });

The POST is made with the code to an Ruby on Rails app in which I use Signet gem to handle the authentication flow, I initialize it following way:

  @client = Signet::OAuth2::Client.new(
      :authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
      :token_credential_uri =>  'https://www.googleapis.com/oauth2/v3/token',
      :client_id => GCAL_CLIENT_KEY,
      :client_secret => GCAL_CLIENT_SECRET,
      :scope => 'email profile',
      additional_parameters: {
          "access_type" => "offline",
          "include_granted_scopes" => "true"
      }
  )

and then try to get the access token:

  @client.code = auth_code
  @client.fetch_access_token!

But getting following exception:

#<Signet::AuthorizationError: Authorization failed.  Server message:
{
 "error": "unsupported_grant_type",
 "error_description": "Invalid grant_type: "
}>

Tried also using HTTP/REST call to https://www.googleapis.com/oauth2/v4/token with request body as described here. But same response - invalid grant_type

1

There are 1 best solutions below

2
user2705223 On

You haven't set a redirect_uri in your Signet gem initialization, and it seems that Signet relies on that to set grant_type to authorization_code: https://github.com/google/signet/blob/621515ddeec1dfb6aef662cdfaca7ab30e90e5a1/lib/signet/oauth_2/client.rb#L834