1

我有以下 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)
              }
            });

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

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

还尝试使用 HTTP/REST 调用与请求正文,如此https://www.googleapis.com/oauth2/v4/token所述。但同样的回应 - 无效的grant_type

4

1 回答 1

0

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

于 2017-07-13T02:06:17.463 回答