I’m working with the google-analytics-data-v1beta
Ruby gem and need to implement user consent flow using OAuth2. My web application requires users to grant permission through a consent screen.
I set up the OAuth2 flow using the google-auth-library-ruby:
require 'googleauth'
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'
require 'redis'
client_secrets = Google::Auth::ClientId.from_file('/config/oauth_secrets.json')
scopes = ['https://www.googleapis.com/auth/analytics.readonly']
store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
auth_handler = Google::Auth::WebUserAuthorizer.new(
client_secrets, scopes, store, '/callback')
get('/auth') do
current_user = session['current_user']
user_creds = auth_handler.get_credentials(current_user, request)
if user_creds.nil?
redirect auth_handler.get_authorization_url(login_hint: current_user, request: request)
end
# Ready to make API calls here
end
get('/callback') do
redirect_path = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
redirect redirect_path
end
The problem is that the Analytics Data client only seems to accept ADC credentials:
require "google/analytics/data/v1beta"
analytics_client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |setup|
setup.credentials = "config/service_account.json"
end
I need to pass user-specific OAuth2 tokens instead. I tried approaches like this but they don’t work:
user_token = Signet::OAuth2::Client.new
user_token.access_token = retrieved_token
analytics_client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |setup|
setup.credentials = user_token
end
Interestingly, the google-apis-analyticsadmin_v1beta
gem accepts custom credentials just fine. How can I configure the Data V1 Beta client to use OAuth2 user credentials instead of service account keys?