Google API:尝试获取访问令牌时,grant_type无效

时间:2017-07-12 17:27:10

标签: ruby-on-rails google-oauth2 google-client google-client-login

我有以下JS代码来获取与Google的OAuth2流程的身份验证代码:

        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)
              }
            });

使用Ruby on Rails应用程序的代码进行POST,我使用Signet gem来处理身份验证流程,我按照以下方式对其进行初始化:

  @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"
      }
  )

然后尝试获取访问令牌:

  @client.code = auth_code
  @client.fetch_access_token!

但是得到以下异常:

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

还尝试使用https://www.googleapis.com/oauth2/v4/token对请求正文进行HTTP / REST调用here。但同样的反应 - 无效的grant_type

1 个答案:

答案 0 :(得分:0)

您尚未在Signet gem初始化中设置redirect_uri,并且Signet似乎依赖于此将grant_type设置为authorization_code:https://github.com/google/signet/blob/621515ddeec1dfb6aef662cdfaca7ab30e90e5a1/lib/signet/oauth_2/client.rb#L834