I'm using a Google service account to make API calls for my Dashing dashboard to Analytics. I'm using the Legato gem to get Analytics data, and authenticating using the gem's wiki's instructions for service accounts.
I've put my Google username and private key into ENV (after base 64-encoding it), and am using dotenv to synchronize these settings between local and Heroku (heroku config
confirms that everything is set correctly). So, my authentication code looks like this:
class GoogleAnalyticsAccount
attr_accessor :user, :profile
# Thanks to the "Service Accounts" section at
# https://github.com/tpitale/legato/wiki/OAuth2-and-Google
def initialize scope="https://www.googleapis.com/auth/analytics.readonly"
client = Google::APIClient.new application_name: '[App name]',
application_version: '1.0'
key = Google::APIClient::PKCS12.load_key(Base64.decode64(ENV['GOOGLE_PRIVATE_KEY_BASE64']), "notasecret")
service_account = Google::APIClient::JWTAsserter.new(ENV['GOOGLE_USER'], scope, key)
client.authorization = service_account.authorize
oauth_client = OAuth2::Client.new("", "", {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
token = OAuth2::AccessToken.new(oauth_client, client.authorization.access_token)
@user = Legato::User.new(token)
end
def profile
@user.profiles.first
end
end
Locally, this code works just fine. On Heroku, I get the following response from Google:
{
"error": "invalid_grant"
}
No more detail than that. Based on extensive Googling, I've found that the two most likely reasons for this are A) I've hit my request limit (but it can't be that, because the same credentials work locally), and B) the server clock isn't synced with NTP. I've set the timezone on Heroku to America/Chicago (same as my local machine), but no dice.
Any ideas? Thanks!