Hopefully someday Google will provide the proper documentation. Here, I list all the steps for integrating authentication on the server side of Google Analytics into ASP.NET C #.
Step 1. Create a project in the Google console
Go to the link https://console.developers.google.com/iam-admin/projects and create a project by clicking the "Create Project" button and specify the project name in the pop-up window and send it.
Step 2. Create credentials and service account
After creating the project, you will be redirected to the "API Manager" page. Click credentials and click the "Create Credentials" button. select "service account key" from the drop-down list, which will be redirected to the next page. From the Tools drop-down list, select New Service Account. Fill in the service account name and download the p12 key. It will have the p12 extension. You will receive a pop-up window with the password " notasecret ", which is the default, and your private key will be downloaded.
Step 3: Create 0auth Client ID
click on the "create credentials" drop-down list and select "0auth Customer ID", you will be redirected to the "Give consent" tab. enter a random name in the text box of the project name. select the type of application as "Web application" and click the "Create" button. Copy the generated customer ID to notepad.
Step 4: Enable the API
On the left side, click on the "Overview" tab and select "Enabled APIs" from the horizontal tab. In the search bar, find "Google Analytics API", click on the drop-down list and click on the "Enable" button. Now, find V4 Analyst Reporting again and turn it on.
Step 5: Install nuget Packages
In visual studio, go to Tools> Nuget Package Manager> Package Manager. Copy paste the following code into the console to install the nuget packages.
Google.Apis.Analytics.v3 Installation Package
Install-Package DotNetOpenAuth.Core -Version 4.3.4.13329
The two packages above are Google Analytics and the DotNetOpenAuth nuget packages.
Step 6: Grant View and Analysis Permission to the Service Account
Go to your Google Analytics account and go to the "Admin" tab and select "User Management" in the left menu, select the domain to which you want to access analytics data and insert the service account email id into it and select "Read and Analyze "resolution from the drop-down list. The service account email id looks like googleanalytics@googleanalytics.iam.gserviceaccount.com.
Working code
FRONT END CODE:
Copy and paste the embed script analytics below into your interface, otherwise you can also get this code from the Google Analytics documentation page.
<script> (function (w, d, s, g, js, fs) { g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } }; js = d.createElement(s); fs = d.getElementsByTagName(s)[0]; js.src = 'https://apis.google.com/js/platform.js'; fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); }; }(window, document, 'script'));</script>
Paste the code below into the body tag of your front page.
<asp:HiddenField ID="accessToken" runat="server" /> <div id="chart-1-container" style="width:600px;border:1px solid #ccc;"></div> <script> var access_token = document.getElementById('<%= accessToken.ClientID%>').value; gapi.analytics.ready(function () { gapi.analytics.auth.authorize({ 'serverAuth': { 'access_token': access_token } }); var dataChart1 = new gapi.analytics.googleCharts.DataChart({ query: { 'ids': 'ga:53861036', </script>
You can also get your id like https://ga-dev-tools.appspot.com/account-explorer/
BACK END CODE:
using System; using System.Linq; using System.Collections.Generic; using System.Collections.Specialized; using System.Web.Script.Serialization; using System.Net; using System.Text; using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Services; using System.Security.Cryptography.X509Certificates; using Google.Apis.Auth.OAuth2; using Google.Apis.Util; using DotNetOpenAuth.OAuth2; using System.Security.Cryptography; namespace googleAnalytics { public partial class api : System.Web.UI.Page { public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly"; string ServiceAccountUser = "googleanalytics@googleanalytics.iam.gserviceaccount.com"; //service account email ID string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension protected void Page_Load(object sender, EventArgs e) { string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY)); accessToken.Value = Token; var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(ServiceAccountUser) { Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = "Google Analytics API" }); string profileId = "ga:53861036"; string startDate = "2016-04-01"; string endDate = "2016-04-30"; string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits"; DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics); GaData data = request.Execute(); List<string> ColumnName = new List<string>(); foreach (var h in data.ColumnHeaders) { ColumnName.Add(h.Name); } List<double> values = new List<double>(); foreach (var row in data.Rows) { foreach (var item in row) { values.Add(Convert.ToDouble(item)); } } values[3] = Math.Truncate(100 * values[3]) / 100; txtSession.Text = values[0].ToString(); txtUsers.Text = values[1].ToString(); txtPageViews.Text = values[2].ToString(); txtBounceRate.Text = values[3].ToString(); txtVisits.Text = values[4].ToString(); } public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope) { // certificate var certificate = new X509Certificate2(keyFilePath, "notasecret"); // header var header = new { typ = "JWT", alg = "RS256" }; // claimset var times = GetExpiryAndIssueDate(); var claimset = new { iss = clientIdEMail, scope = scope, aud = "https://accounts.google.com/o/oauth2/token", iat = times[0], exp = times[1], }; JavaScriptSerializer ser = new JavaScriptSerializer(); // encoded header var headerSerialized = ser.Serialize(header); var headerBytes = Encoding.UTF8.GetBytes(headerSerialized); var headerEncoded = Convert.ToBase64String(headerBytes); // encoded claimset var claimsetSerialized = ser.Serialize(claimset); var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized); var claimsetEncoded = Convert.ToBase64String(claimsetBytes); // input var input = headerEncoded + "." + claimsetEncoded; var inputBytes = Encoding.UTF8.GetBytes(input); // signature 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 = Convert.ToBase64String(signatureBytes); // jwt var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded; var client = new WebClient(); client.Encoding = Encoding.UTF8; var uri = "https://accounts.google.com/o/oauth2/token"; var content = new NameValueCollection(); content["assertion"] = jwt; content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"; string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content)); var result = ser.Deserialize<dynamic>(response); object pulledObject = null; string token = "access_token"; if (result.ContainsKey(token)) { pulledObject = result[token]; } //return result; return pulledObject; } 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 }; } } }