I am trying to use Google Analytics Embed API Server Side authorization using C#, the code is as follows
public ActionResult Dashboard()
{
ViewBag.Message = "Dashboard.";
var scopes = new string[]
{
AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
AnalyticsService.Scope.AnalyticsReadonly,
AnalyticsService.Scope.AnalyticsEdit
};
const string serviceAccountEmail = "526261635050-fofbfeicvbpgumafa114te878787878@developer.gserviceaccount.com";
const string keyFilePath = @"D:\key.p12";
var status = RequestAccessTokenAsync(keyFilePath,scopes,serviceAccountEmail);
ViewBag.Token = _accessToken;
return View();
}
private async Task<bool> RequestAccessTokenAsync(string certificateFile, string[] scope, string serviceAccount)
{
var certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccount)
{
Scopes = scope
}.FromCertificate(certificate));
var status = await serviceAccountCredential.RequestAccessTokenAsync(CancellationToken.None);
if (status)
_accessToken = serviceAccountCredential.Token.AccessToken;
return status;
}
Making an instance of Service works fine and is also able to fetch the raw data but we need to use the Embed API and the problem is that there is no value retrieved in _accessToken and we need that to be able to access the embedded API.
Any ideas / thoughts will be helpful.
On google demo site, the example provided is for python - https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/
Try this:
public ActionResult Dashboard()
{
ViewBag.Message = "Dashboard.";
var scopes = new string[]
{
AnalyticsService.Scope.Analytics, // view and manage your Google Analytics data
AnalyticsService.Scope.AnalyticsReadonly,
AnalyticsService.Scope.AnalyticsEdit
};
const string serviceAccountEmail = "526261635050-fofbfeicvbpgumafa114te878787878@developer.gserviceaccount.com";
const string keyFilePath = @"D:\key.p12";
var certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scope
}.FromCertificate(certificate));
Task<string> task = ((ITokenAccess)serviceAccountCredential).GetAccessTokenForRequestAsync();
task.Wait();
var _accessToken = task.Result;
ViewBag.Token = _accessToken;
return View();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With