Techioz Blog

Google Analytics V1 クライアント - 認証情報の種類を変更できません

概要

google-analytics-data-v1beta Ruby クライアント ライブラリを使用して Google Analytics V1 API と対話しようとしています。

ただし、Web アプリのユーザーからの許可が必要なため、同意画面 (3-Legged OAuth2 フロー) を追加しました。

私が従った(Web)例は、認証 google-auth-library-ruby のドキュメントにあるものです。

require 'googleauth'
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'
require 'redis'

client_id = Google::Auth::ClientId.from_file('/path/to/client_secrets.json')
scope = ['https://www.googleapis.com/auth/drive']
token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
authorizer = Google::Auth::WebUserAuthorizer.new(
  client_id, scope, token_store, '/oauth2callback')


get('/authorize') do
  # NOTE: Assumes the user is already authenticated to the app
  user_id = request.session['user_id']
  credentials = authorizer.get_credentials(user_id, request)
  if credentials.nil?
    redirect authorizer.get_authorization_url(login_hint: user_id, request: request)
  end
  # Credentials are valid, can call APIs
  # ...
end

get('/oauth2callback') do
  target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(
    request)
  redirect target_url
end

認証情報が利用可能な行で Google Analytics Data V1 ベータ API を呼び出すことができるようですが、Google Analytics Data V1 ライブラリをチェックすると、上記の認証情報を渡す方法が見つからず、ADC (アプリケーションのデフォルト) を使用することを余儀なくされました。 Credentials) を使用して認証しますが、これは自分の Google アカウントに権限を与えるためだけです。

Google Analytics データ V1 ベータ版ドキュメントの抜粋: ここ

require "google/analytics/data/v1beta"

client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
  config.credentials = "path/to/credentialfile.json"
end

また、google-apis-analyticsadmin_v1beta ライブラリは他の認証情報タイプを追加しても正常に動作し、次のものが機能することがわかりました。

credentials = Signet::OAuth2::Client.new
credentials.access_token = token # user's access token

google_analytics_admin_client = ::Google::Apis::AnalyticsadminV1beta::GoogleAnalyticsAdminService.new
google_analytics_admin_client.authorization = credentials

accounts = google_analytics_admin_client.list_accounts

何かが足りないような気がします。

私が試したこと:

ADC (アプリケーションのデフォルト認証情報) とは異なる認証情報を渡す方法を探していました。

次のようなもの:

credentials = Signet::OAuth2::Client.new
credentials.access_token = access_token # User's access token

client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
  config.credentials = credentials
end

# OR -------

user_id = request.session['user_id']
credentials = authorizer.get_credentials(user_id, request)

client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
  config.credentials = credentials
end

解決策

実用的な例が見つかりました。

credentials = Signet::OAuth2::Client.new # Can be any credentials object
credentials.access_token = access_token # User's access token

client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
  config.credentials = credentials
end

これは質問で言及されているのと同じスニペットですが、機能します。