google-analytics-api
認証
サーチ…
構文
- GET https://accounts.google.com/o/oauth2/auth?client_id= {clientid}&redirect_uri = urn:ietf:wg:oauth:2.0:oob&scope = {スコープ}&response_type = code
- POST https://accounts.google.com/o/oauth2/token code = {上記コードからのコード}&client_id = {ClientId}&client_secret = {ClientSecret}&redirect_uri = urn:ietf:wg:oauth:2.0:oob&grant_type = authorization_code
- POST https://accounts.google.com/o/oauth2/token client_id = {ClientId}&client_secret = {ClientSecret}&refresh_token = {上記の呼び出しから}&grant_type = refresh_token
パラメーター
パラメータ | 説明 |
---|---|
クライアントID | Googleデベロッパーコンソールからプロジェクトやアプリケーションを特定する |
秘密の | Googleデベロッパーコンソールからプロジェクトやアプリケーションを特定する |
redirect_uri | 認証が返されるべきGoogle Developerの場所から。ネイティブアプリケーションの場合urn:ietf:wg:oauth:2.0:oob を使用してローカルホストを示すことができます |
備考
Google APIにアクセスするには、自分を開発者として特定し、プロジェクトを特定する必要があります。 Google Developersコンソールで新しいプロジェクトを作成することでそれを行います。
プロジェクトを作成する際に、GoogleアナリティクスAPIにアクセスするには、アクセスするAPIを有効にする必要があります。
- レポートAPI :GoogleアナリティクスレポートAPI v4へのアクセス。
- Analytics API :他のすべてにアクセスできます。
今すぐデータにアクセスする方法を決定する必要があります。
Google Dataには、Data PublicとPrivateの2種類があります。
- パブリックデータはユーザーによって所有されていません。メタデータAPIは、そのデータにアクセスするためにログインする必要のないパブリックAPIです。
- レポートAPIには、ユーザーのGoogleアナリティクスデータが含まれています。ユーザーがアクセス権を与えていない限り、非表示にすることはできません。
公開データにのみアクセスする場合は、公開APIキーを作成するだけで問題のAPIにアクセスできます。プライベートユーザーデータにアクセスする場合は、Oauth2資格情報またはサービスアカウント資格情報のいずれかを作成する必要があります。
権限Oauth2
プライベートユーザデータにアクセスするには、アクセスするためにデータ所有者の許可が必要です。 Oauth2では、ユーザーからのアクセスを要求できます。
以前はOauth2の前に見たことがあります。
アプリケーション "Google Analytics Windows"がユーザーに "Google Analyticsデータ"を表示するためのアクセス権を要求しています
- Googleアナリティクスウィンドウは、Googleデベロッパーコンソールで作成されたプロジェクトの名前です。
- Google Analyticsデータは、私たちが求めた権限の範囲です。
スコープ GoogleアナリティクスAPIの目的は、使用できるスコープが2つあることをユーザーに伝える必要があります。
必要な範囲だけを要求するのが最善です。ユーザーデータのみを読む場合は、読み取り専用範囲を要求する必要があります。
認可サービスアカウント
サービスアカウントは、事前承認されている点で異なります 。サービスアカウントの資格情報を作成する場合、開発者はサービスアカウントのメールを受け取り、Googleアナリティクスアカウントのユーザーとして追加できます。アカウントレベルでは、サービスアカウントにデータへのアクセス権が付与されます。認証ウィンドウをポップアップしてアクセスを要求する必要はありません。サービスアカウントは、Googleアナリティクスアカウントのユーザーである限り、そのデータにアクセスできます。
結論
GoogleアナリティクスAPIによって公開されるほとんどのデータにアクセスするには、認証が必要です。
2015年5月現在、クライアントのログイン/ログインとパスワードを使用してGoogle APIにアクセスすることはできません。オープン認証を使用する必要があります。
**
Oauth2 C#
例では、 Google APIのDotnetクライアントライブラリを使用しています 。
PM>インストールパッケージGoogle.Apis.AnalyticsReporting.v4
/// <summary>
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static AnalyticsReportingService AuthenticateOauth(string clientSecretJson, string userName)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new Exception("userName is required.");
if (string.IsNullOrEmpty(clientSecretJson))
throw new Exception("clientSecretJson is required.");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need.
string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // View your Google Analytics Data
UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = string.Format("{0} Authentication", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name),
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message);
throw new Exception("CreateOauth2DriveFailed", ex);
}
}
サービスアカウント認証Vb.net
サンプルはInstall-Package Google.Apis.AnalyticsReporting.v4を使用します
Public Shared Function getServiceInitializer() As BaseClientService
Dim serviceAccountCredentialFilePath = "Path to Json service account key file" REM from Google Developers console
Dim myKeyEMail = "XXX@developer.gserviceaccount.com" REM from Google Developers console
Dim scope = Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly
Try
Dim credential
Using stream As New FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read)
credential = GoogleCredential.FromStream(stream).CreateScoped(scope)
End Using
Dim Initializer As New BaseClientService.Initializer()
Initializer.HttpClientInitializer = credential
Initializer.ApplicationName = "SRJCGMail"
Dim service As New AnalyticsReportingService(Initializer)
Return service
Catch ex As Exception
Console.WriteLine(ex.Message)
Return Nothing
End Try
End Function