I have a bunch of keys : client id, client secret, api key
But all the documentation show authentication using human interaction.
How do I use the dot net libraries for interacting with the Google API v3 and the AnalyticsService without user interaction? If I just use the API Key, I get "Google.Apis.Requests.RequestError Login Required"
There are no samples that I can find anywhere that do this.
EDIT : this is for one Google Analytics account, I have full access to it, username, password, client id, client secret, api/developer key, everything. I just want to have the utility download data without me everyday.
Here is my working code, this is for a console application that I call through a batch file process.
I am not a .Net developer so this code may not be perfect, if you see any areas for improvements lets me know!
Error handling is minimal as I do not want one failure to kill the batch
I am using the registry to store the access token and expire time
Also have the privatekey.p12 files in the application folder
The account is a User not an Admin on the profile.
Also posted here https://groups.google.com/forum/?fromgroups=#!topic/google-analytics-data-export-api/quIN0vX-psw
Example command line call:
C:\DW\GoogleAnalyticsNicheSites\GoogleAnalyticsNicheSites.exe "ga:XXXX9049" "2012-04-01" "2012-04-01" "ga:visitors,ga:newVisits,ga:visits,ga:bounces,ga:pageviews" "ga:date,ga:medium" "XXXXXXXXXXXXXXXXXXXXXXXXXXXX-privatekey.p12" "XXXXX...@developer.gserviceaccount.com" "RegKey" > C:\Data\NicheSites\ga_58589049_moneyjobs.com_20120401.txt"
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Microsoft.Win32;
using Newtonsoft.Json;
namespace ConsoleApplication5
{
class Program
{
public static string access_token = "";
public static string expire_time = string.Empty;
public static string profileId = string.Empty;
public static string metrics = string.Empty;
public static string dimensions = string.Empty;
public static string startDate = string.Empty;
public static string endDate = string.Empty;
public static string privatekeyFile = string.Empty;
public static string loginEmail = string.Empty;
public static string regKeyName = string.Empty;
static void Main(string[] args)
{
profileId = args[0];
startDate = args[1];
endDate = args[2];
metrics = args[3];
dimensions = args[4];
privatekeyFile = args[5];
loginEmail = args[6];
regKeyName = args[7];
try
{
// certificate
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
var directory = System.IO.Path.GetDirectoryName(path).Remove(0, 6);
var certificate = new X509Certificate2(directory + "\\" + privatekeyFile , "notasecret");
try
{
expire_time = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\CB\" + regKeyName).GetValue("ExpireTime").ToString();
}
catch (Exception e)
{
RegistryKey key;
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
key.SetValue("OAuthToken", "");
key.Close();
}
try
{
access_token = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\CB\" + regKeyName).GetValue("OAuthToken").ToString();
}
catch (Exception e)
{
RegistryKey key;
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
key.SetValue("ExpireTime", DateTime.UtcNow.AddSeconds(3500).ToString("MM/dd/yyyy HH:mm:ss"));
key.Close();
}
if (expire_time == null || expire_time.Length < 4)
{
expire_time = "01/01/2000";
}
var ExpireDateTime = Convert.ToDateTime(expire_time);
var ExpireTimeNow = DateTime.UtcNow;
TimeSpan span = ExpireDateTime - ExpireTimeNow;
double iExpireLeft = span.TotalSeconds;
if (iExpireLeft < 60)
{
// header
var header = new { typ = "JWT", alg = "RS256" };
// claimset
var times = GetExpiryAndIssueDate();
var claimset = new
{
iss = loginEmail,
scope = "https://www.googleapis.com/auth/analytics.readonly",
aud = "https://accounts.google.com/o/oauth2/token",
iat = times[0],
exp = times[1],
};
// encoded header
var headerSerialized = JsonConvert.SerializeObject(header);
var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
var headerEncoded = Base64UrlEncode(headerBytes);
// encoded claimset
var claimsetSerialized = JsonConvert.SerializeObject(claimset);
var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
var claimsetEncoded = Base64UrlEncode(claimsetBytes);
// input
var input = headerEncoded + "." + claimsetEncoded;
var inputBytes = Encoding.UTF8.GetBytes(input);
// signiture
var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
var cspParam = new CspParameters
{
KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
};
var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
var signatureEncoded = Base64UrlEncode(signatureBytes);
// jwt
var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;
var client = new HttpClient();
var uri = "https://accounts.google.com/o/oauth2/token";
var post = new Dictionary<string, string>
{
{"assertion", jwt},
{"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"}
};
var content = new FormUrlEncodedContent(post);
var result = client.PostAsync(uri, content).Result;
RootObject values = JsonConvert.DeserializeObject<RootObject>(result.Content.ReadAsStringAsync().Result);
access_token = values.access_token;
RegistryKey key;
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
key.SetValue("OAuthToken", access_token);
key.Close();
key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\CB\" + regKeyName);
key.SetValue("ExpireTime", DateTime.UtcNow.AddSeconds(3500).ToString("MM/dd/yyyy HH:mm:ss"));
key.Close();
}
// Create the service.
var service = new AnalyticsService();
ListAnalytics(service);
}
catch (Exception e)
{
Console.WriteLine(profileId + ": " + e.Message + " " + e.Source + " " + e.StackTrace);
}
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
state.AccessToken = access_token;
string authCode = access_token;
arg.RefreshToken(state);
return state;
}
private static void ListAnalytics(AnalyticsService service)
{
try
{
var iCount = 1;
var iStartIndex = 1;
while (iCount > 0 )
{
var response = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
response.Dimensions = dimensions;
response.MaxResults = 10000;
response.StartIndex = iStartIndex;
response.Oauth_token = access_token;
GaData report = response.Fetch();
Console.Write("ids|");
for (int i = 0; i <= report.ColumnHeaders.Count - 2; i++)
{
Console.Write(report.ColumnHeaders[i].Name.ToString() + "|");
}
Console.WriteLine(report.ColumnHeaders[report.ColumnHeaders.Count - 1].Name.ToString());
if (null != report.Rows.Count)
{
for (int i = 0; i < report.Rows.Count; i++)
{
IList<string> row = report.Rows[i];
Console.Write(profileId + "|");
for (int x = 0; x <= row.Count - 2; x++)
{
Console.Write(row[x].ToString() + "|");
}
Console.WriteLine(row[row.Count - 1].ToString());
}
//Console.ReadLine();
iCount = report.Rows.Count < 10000 ? 0 : 1;
}
else
{
iCount = 0;
}
iStartIndex += 10000;
}
}
catch (Exception ex)
{
}
}
private static int[] GetExpiryAndIssueDate()
{
var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var issueTime = DateTime.UtcNow;
var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;
return new[] { iat, exp };
}
private static string Base64UrlEncode(byte[] input)
{
var output = Convert.ToBase64String(input);
output = output.Split('=')[0]; // Remove any trailing '='s
output = output.Replace('+', '-'); // 62nd char of encoding
output = output.Replace('/', '_'); // 63rd char of encoding
return output;
}
public class RootObject
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
}
//public static Google.Apis.Authentication.IAuthenticator UseSavedAuthorization()
//{
// var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
// provider.ClientIdentifier = "XXXXXXXXXXXXXXXXX-6ogef1100hmt92k8frqaprhfr38b4oaq.apps.googleusercontent.com";
// provider.ClientSecret = "XXXXXXXXXXXXXXXXXXXXXX";
// AuthenticatorFactory.GetInstance().RegisterAuthenticator(() => new OAuth2Authenticator(provider, GetAuthentication));
// OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getState);
// auth.LoadAccessToken();
// return auth;
//}
//public static IAuthorizationState getState(NativeApplicationClient arg)
//{
// IAuthorizationState state = new AuthorizationState(new[] { AnalyticsService.Scopes.AnalyticsReadonly.ToString() });
// state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
// state.RefreshToken = access_token;
// arg.RefreshToken(state);
// return state;
//}
}
}