【问题标题】:Google API: Invalid grant_type when trying to get access tokenGoogle API:尝试获取访问令牌时授权类型无效
【发布时间】:2025-11-27 12:15:02
【问题描述】:

我有以下 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 应用程序的代码制作的,在该应用程序中我使用 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: "
}>

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 我尝试将redirect_uri 设置为我在控制台中设置的其中一个,不幸的是结果相同。
    • 另外 - 问题也与 HTTP/REST 有关 - 所以与 Signet 无关