Trouble with Google Apps API and Service Accounts in Ruby

天大地大妈咪最大 提交于 2019-12-01 08:32:05

This looks to me like you are using an older example. I think that's how you used to do it about a year ago. Back in late 2012 that method of setting up the app was deprecated because Signet was updated to handle all aspects of the OAuth2 setup.

Here is the code I generally use to create a service account. You can tweak it to fit into your method.

client.authorization = Signet::OAuth2::Client.new(
 :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
 :audience => 'https://accounts.google.com/o/oauth2/token',
 :scope => "https://www.googleapis.com/auth/drive",
 :issuer => "<service account email>@developer.gserviceaccount.com",
 :signing_key => Google::APIClient::KeyUtils.load_from_pkcs12("<private key file>-privatekey.p12", "notasecret"),
 :person => "<users email address>")
client.authorization.fetch_access_token!

If you are still having issues let me know and I'll see if I can help.

I have worked with service account+Drive+file permissions using Java. In order to use permissions for a particular user, I had to allow certain scope. The only thing I can guess about your issue is that you might have missed the Delegation part

Using version 0.9.13 of google-api-client, I succeeded in using the following slight adaptation of Woodward's answer (note the absence of the person parameter):

def service_account_authorization(credentials_file, scope)
  credentials = JSON.parse(File.open(credentials_file, 'rb').read)
  authorization = Signet::OAuth2::Client.new(
    :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
    :audience => 'https://accounts.google.com/o/oauth2/token',
    :scope => scope,
    :issuer => credentials['client_id'],
    :signing_key => OpenSSL::PKey::RSA.new(credentials['private_key'], nil),
  )
  authorization.fetch_access_token!
  authorization
end

This snippet takes a file as it was downloaded from Google Cloud Console for a service account and returns an auth object that can be fed to Google::Apis::*Service.authorization.

Thanks James!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!