【问题标题】:How to handle the grant_type error with the google_drive gem?如何使用 google_drive gem 处理 grant_type 错误?
【发布时间】:2020-05-20 01:03:08
【问题描述】:

我正在尝试使用 Ruby gem 'google_drive'。在使用该 gem 之前,我通过 gem omniauth-google-oauth2 获取用户的令牌。

当我尝试按如下方式使用 google_drive 时:

  def google_oauth2(current_user)

    session = GoogleDrive.login_with_oauth(self.token)

    # Gets list of remote files.
    session.files.each do |file|
      p file.title
    end
  end 

我收到以下错误:

Sending HTTP get https://www.googleapis.com/drive/v3/files?fields=%2A
Caught error Authorization failed.  Server message:
{
 "error": "invalid_request",
 "error_description": "Required parameter is missing: grant_type"
}
Error - #<Signet::AuthorizationError: Authorization failed.  Server message:
{
 "error": "invalid_request",
 "error_description": "Required parameter is missing: grant_type"
}>

Completed 500 Internal Server Error in 128ms (ActiveRecord: 0.4ms)

我该如何解决这个问题?

更新

用于存储 google oauth 2 令牌的 Omniauth 代码:

  def google_oauth2
    auth_hash = request.env['omniauth.auth']

    @authentication = Authentication.find_or_create_by(
                                            user_id: current_user.id,
                                            provider: auth_hash["provider"],
                                            uid: auth_hash["uid"]
                                          )
    @authentication.update_attributes(
                                      :token => auth_hash['credentials']['token'],
                                      :refresh_token => auth_hash['credentials']['refresh_token'],
                                      :provider_description => auth_hash["info"].email
                                    )

    flash[:notice] = "google_oauth2 authed."
    redirect_to '/'
  end

【问题讨论】:

标签: ruby-on-rails ruby google-drive-api omniauth


【解决方案1】:

无需 config.json 即可访问 google drive api 的工作解决方案。此方案使用从 google auth 2 omniauth 策略获取的刷新令牌:

  require 'google/apis/drive_v2'
    auth = Signet::OAuth2::Client.new(
      token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
      client_id:            "XXX-XXX",
      client_secret:        "XXX",
      refresh_token:        self.refresh_token # Get this from the omniauth strategy. 
    )

    auth.fetch_access_token!

    x = Google::Apis::DriveV2
    drive = x::DriveService.new
    drive.authorization = auth

files = drive.list_files

这花了我 0.5 天。我希望它可以帮助其他人! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2013-08-06
    相关资源
    最近更新 更多