Use the Google Analytics API to display information in C #

I have been looking for a good solution all day, but google is developing so fast that I can’t find something working. What I want to do is that I have a web application that has an admin section in which the user needs to log in to view the information. In this section, I want to show some data from GA, such as pageviews for some specific URLs. Since this is not the user information that I display, but the google analytics user, I want to enable the transfer of information (username / password or APIKey), but I can’t find out how to do this. The entire sample I found uses OAuth2 (the witch, if I understand, will ask the visitor to log in using Google).

What I have found so far:

Maybe I'm just tired, and tomorrow it will be easy to find a solution, but now I need help!

thank

+45
c # google-api google-analytics-api
Apr 24 2018-12-12T00:
source share
7 answers

I searched many times and finally searched the code from several places and then wrapped my own interface around it, I came up with the following solution. Not sure if people paste all their code here, but I think, why not save everyone else :)

Prerequisites, you will need to install the Google.GData.Client package and google.gdata.analytics/dll.

This is the main class that does the job.

namespace Utilities.Google { public class Analytics { private readonly String ClientUserName; private readonly String ClientPassword; private readonly String TableID; private AnalyticsService analyticsService; public Analytics(string user, string password, string table) { this.ClientUserName = user; this.ClientPassword = password; this.TableID = table; // Configure GA API. analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0"); // Client Login Authorization. analyticsService.setUserCredentials(ClientUserName, ClientPassword); } /// <summary> /// Get the page views for a particular page path /// </summary> /// <param name="pagePath"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="isPathAbsolute">make this false if the pagePath is a regular expression</param> /// <returns></returns> public int GetPageViewsForPagePath(string pagePath, DateTime startDate, DateTime endDate, bool isPathAbsolute = true) { int output = 0; // GA Data Feed query uri. String baseUrl = "https://www.google.com/analytics/feeds/data"; DataQuery query = new DataQuery(baseUrl); query.Ids = TableID; //query.Dimensions = "ga:source,ga:medium"; query.Metrics = "ga:pageviews"; //query.Segment = "gaid::-11"; var filterPrefix = isPathAbsolute ? "ga:pagepath==" : "ga:pagepath=~"; query.Filters = filterPrefix + pagePath; //query.Sort = "-ga:visits"; //query.NumberToRetrieve = 5; query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); Uri url = query.Uri; DataFeed feed = analyticsService.Query(query); output = Int32.Parse(feed.Aggregates.Metrics[0].Value); return output; } public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate) { // GA Data Feed query uri. String baseUrl = "https://www.google.com/analytics/feeds/data"; DataQuery query = new DataQuery(baseUrl); query.Ids = TableID; query.Dimensions = "ga:pagePath"; query.Metrics = "ga:pageviews"; //query.Segment = "gaid::-11"; var filterPrefix = "ga:pagepath=~"; query.Filters = filterPrefix + pagePathRegEx; //query.Sort = "-ga:visits"; //query.NumberToRetrieve = 5; query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); Uri url = query.Uri; DataFeed feed = analyticsService.Query(query); var returnDictionary = new Dictionary<string, int>(); foreach (var entry in feed.Entries) returnDictionary.Add(((DataEntry)entry).Dimensions[0].Value, Int32.Parse(((DataEntry)entry).Metrics[0].Value)); return returnDictionary; } } } 

And this is the interface and implementation that I use to complete it.

 namespace Utilities { public interface IPageViewCounter { int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true); Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate); } public class GooglePageViewCounter : IPageViewCounter { private string GoogleUserName { get { return ConfigurationManager.AppSettings["googleUserName"]; } } private string GooglePassword { get { return ConfigurationManager.AppSettings["googlePassword"]; } } private string GoogleAnalyticsTableName { get { return ConfigurationManager.AppSettings["googleAnalyticsTableName"]; } } private Analytics analytics; public GooglePageViewCounter() { analytics = new Analytics(GoogleUserName, GooglePassword, GoogleAnalyticsTableName); } #region IPageViewCounter Members public int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true) { int output = 0; try { output = analytics.GetPageViewsForPagePath(relativeUrl, startDate, endDate, isPathAbsolute); } catch (Exception ex) { Logger.Error(ex); } return output; } public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate) { var input = analytics.PageViewCounts(pagePathRegEx, startDate, endDate); var output = new Dictionary<string, int>(); foreach (var item in input) { if (item.Key.Contains('&')) { string[] key = item.Key.Split(new char[] { '?', '&' }); string newKey = key[0] + "?" + key.FirstOrDefault(k => k.StartsWith("p=")); if (output.ContainsKey(newKey)) output[newKey] += item.Value; else output[newKey] = item.Value; } else output.Add(item.Key, item.Value); } return output; } #endregion } } 

And now everything else - the obvious stuff - you will need to add the web.config values ​​to your application or webconfig configuration and call IPageViewCounter.GetPageViewCount

+29
Apr 24 '12 at 23:17
source share

This requires a bit of google setup, but it's actually quite simple. I will list step by step.

First you need to create an application in the Google Cloud Console and enable the Google Analytics API.

  • Go to http://code.google.com/apis/console
  • Select the drop-down list and create a project if you do not already have it.
  • After creating the project, click on services
  • Now enable the Google Analytics API

Now that the Google Analytics API is turned on, the next step will be to enable the service account to access your analytics profiles / sites. A service account allows you to log in without prompting for user credentials.

  • Go to http://code.google.com/apis/console and select the project that you created from the drop-down list.
  • Next, go to the "Access to API" section and click the "Create another client identifier" button.
  • In the Create Customer ID window, select a service account and click Create Customer ID.
  • Download the public key for this account; if it does not start, download it automatically. You will need this later when you authorize.
  • Before you close the copy, automatically create the service email address that you will need in the next step. Customer email looks like @ developer.gserviceaccount.com

Now that we have a service account, you need to allow this service account to access your profiles / sites in Google Analytics.

  • Sign in to Google Analytics.
  • After entering the system, click the "Administrator" button in the upper right corner of the screen.
  • In Admin, click on the drop-down list of the account and select the account / site on which you want to access your service account, then click "User Management" in the account section.
  • Enter the email address that was created for your service account and let it read and analyze the permission.
  • Repeat these steps for any other account / site that you want your service to have access to.

Now that the setup is done for the service account to access Google Analytics through the API, we can start the code.

Get this package from NuGet:

Google.Apis.Analytics.v3 Client Library

Add the following data:

 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 System.Collections.Generic; using System.Linq; 

Some things to note.

  • keyPath is the path to the key file that you downloaded with the .p12 file extension.
  • accountEmailAddress is the api letter we received earlier.
  • Scope is an Enum in the Google.Apis.Analytics.v3.AnalyticService class that defines the URL for authorization (ex: AnalyticsService.Scope.AnalyticsReadonly ).
  • The application name is the name of your choice that tells the google api that it is being accessed (aka: this may be what you ever choose).

Then the code for making some basic calls is as follows.

 public class GoogleAnalyticsAPI { public AnalyticsService Service { get; set; } public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress) { var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable); var credentials = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(accountEmailAddress) { Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly } }.FromCertificate(certificate)); Service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credentials, ApplicationName = "WorthlessVariable" }); } public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate) { AnalyticDataPoint data = new AnalyticDataPoint(); if (!profileId.Contains("ga:")) profileId = string.Format("ga:{0}", profileId); //Make initial call to service. //Then check if a next link exists in the response, //if so parse and call again using start index param. GaData response = null; do { int startIndex = 1; if (response != null && !string.IsNullOrEmpty(response.NextLink)) { Uri uri = new Uri(response.NextLink); var paramerters = uri.Query.Split('&'); string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1]; startIndex = int.Parse(s); } var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex); response = request.Execute(); data.ColumnHeaders = response.ColumnHeaders; data.Rows.AddRange(response.Rows); } while (!string.IsNullOrEmpty(response.NextLink)); return data; } private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate, int startIndex) { DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics)); request.Dimensions = string.Join(",", dimensions); request.StartIndex = startIndex; return request; } public IList<Profile> GetAvailableProfiles() { var response = Service.Management.Profiles.List("~all", "~all").Execute(); return response.Items; } public class AnalyticDataPoint { public AnalyticDataPoint() { Rows = new List<IList<string>>(); } public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; } public List<IList<string>> Rows { get; set; } } } 



Other links that will be useful:

Analytical API - Internet Query API

Explorer Analytical API Version 2 - Internet Query API

Link to dimensions and metrics

Hope this helps someone who is trying to do this in the future.

+77
Oct. 10 '13 at 15:26
source share

I was hoping to just add a comment to the answer for the v3 beta, but the rep dots prevent this. However, I thought it would be nice if others had such information, like this:

 using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using System.Security.Cryptography.X509Certificates; using Google.Apis.Services; 

These namespaces are used throughout the code in this post. I always wanted people to publish namespaces more often, I seem to spend a lot of time looking for them. Hope this saves a few people a few minutes of work.

+11
Jan 16 '14 at 18:28
source share

I installed something very similar to the above answer in the nuGet package. He does the following: - connects to the "service account" configured in the API console - Pulls out any Google Analytics data that you would like - displays data using the Google Graphics API and it’s very easy to change. You can see more here: https://www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/ .

+3
Sep 21 '13 at 4:39 on
source share

This answer is for those of you who want to access your own Google Analytics account and want to use the new Google Analytics v4 reporting API .

I recently wrote a post on how to get Google Analytics data using C #. Read all the details there.

First you need to choose between connecting to OAuth2 or a service account. I assume that you have a Google Analytics account, so you need to create a “service account key” on the Credentials Google API page.

Once you create it, upload the JSON file and put it in your project (I put it in my App_Data folder).

Then install the Google.Apis.AnalyticsReporting.v4 Nuget package. Also install Newtonsoft Json.NET .

Include this class in your project:

 public class PersonalServiceAccountCred { public string type { get; set; } public string project_id { get; set; } public string private_key_id { get; set; } public string private_key { get; set; } public string client_email { get; set; } public string client_id { get; set; } public string auth_uri { get; set; } public string token_uri { get; set; } public string auth_provider_x509_cert_url { get; set; } public string client_x509_cert_url { get; set; } } 

And here is what you expect: a complete example!

 string keyFilePath = Server.MapPath("~/App_Data/Your-API-Key-Filename.json"); string json = System.IO.File.ReadAllText(keyFilePath); var cr = JsonConvert.DeserializeObject(json); var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email) { Scopes = new[] { AnalyticsReportingService.Scope.Analytics } }.FromPrivateKey(cr.private_key)); using (var svc = new AnalyticsReportingService( new BaseClientService.Initializer { HttpClientInitializer = xCred, ApplicationName = "[Your Application Name]" }) ) { // Create the DateRange object. DateRange dateRange = new DateRange() { StartDate = "2017-05-01", EndDate = "2017-05-31" }; // Create the Metrics object. Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" }; //Create the Dimensions object. Dimension browser = new Dimension { Name = "ga:browser" }; // Create the ReportRequest object. ReportRequest reportRequest = new ReportRequest { ViewId = "[A ViewId in your account]", DateRanges = new List() { dateRange }, Dimensions = new List() { browser }, Metrics = new List() { sessions } }; List requests = new List(); requests.Add(reportRequest); // Create the GetReportsRequest object. GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests }; // Call the batchGet method. GetReportsResponse response = svc.Reports.BatchGet(getReport).Execute(); } 

We start by deserializing the service account key information from the JSON file and converting it into a PersonalServiceAccountCred object. Then we create a ServiceAccountCredential and connect to Google through AnalyticsReportingService . Using this service, we then prepare some basic filters for moving to the API and sending a request.

It is probably best to set a breakpoint on the line where the response variable is declared, press F10 once, then move the cursor over the variable so that you can see what data is available for use in the response.

+3
Jun 17 '17 at 2:29 on
source share

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 () { /** * Authorize the user with an access token obtained server side. */ gapi.analytics.auth.authorize({ 'serverAuth': { 'access_token': access_token } }); /** * Creates a new DataChart instance showing sessions. * It will be rendered inside an element with the id "chart-1-container". */ var dataChart1 = new gapi.analytics.googleCharts.DataChart({ query: { 'ids': 'ga:53861036', // VIEW ID <-- Goto your google analytics account and select the domain whose analytics data you want to display on your webpage. From the URL ex: a507598w53044903p53861036. Copy the digits after "p". It is your view ID 'start-date': '2016-04-01', 'end-date': '2016-04-30', 'metrics': 'ga:sessions', 'dimensions': 'ga:date' }, chart: { 'container': 'chart-1-container', 'type': 'LINE', 'options': { 'width': '100%' } } }); dataChart1.execute(); /** * Creates a new DataChart instance showing top 5 most popular demos/tools * amongst returning users only. * It will be rendered inside an element with the id "chart-3-container". */ }); </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 }; } } } 
+1
May 31 '16 at 6:31
source share

Another working approach

Add the code below to ConfigAuth

  var googleApiOptions = new GoogleOAuth2AuthenticationOptions() { AccessType = "offline", // can use only if require ClientId = ClientId, ClientSecret = ClientSecret, Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = context => { context.Identity.AddClaim(new Claim("Google_AccessToken", context.AccessToken)); if (context.RefreshToken != null) { context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken)); } context.Identity.AddClaim(new Claim("GoogleUserId", context.Id)); context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString())); var expiresInSec = 10000; context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString())); return Task.FromResult(0); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie }; googleApiOptions.Scope.Add("openid"); // Need to add for google+ googleApiOptions.Scope.Add("profile");// Need to add for google+ googleApiOptions.Scope.Add("email");// Need to add for google+ googleApiOptions.Scope.Add("https://www.googleapis.com/auth/analytics.readonly"); app.UseGoogleAuthentication(googleApiOptions); 

Add below code, namespaces and relative links

  using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Services; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; using System; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; public class HomeController : Controller { AnalyticsService service; public IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } public async Task<ActionResult> AccountList() { service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = await GetCredentialForApiAsync(), ApplicationName = "Analytics API sample", }); //Account List ManagementResource.AccountsResource.ListRequest AccountListRequest = service.Management.Accounts.List(); //service.QuotaUser = "MyApplicationProductKey"; Accounts AccountList = AccountListRequest.Execute(); return View(); } private async Task<UserCredential> GetCredentialForApiAsync() { var initializer = new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = ClientId, ClientSecret = ClientSecret, }, Scopes = new[] { "https://www.googleapis.com/auth/analytics.readonly" } }; var flow = new GoogleAuthorizationCodeFlow(initializer); var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie); if (identity == null) { Redirect("/Account/Login"); } var userId = identity.FindFirstValue("GoogleUserId"); var token = new TokenResponse() { AccessToken = identity.FindFirstValue("Google_AccessToken"), RefreshToken = identity.FindFirstValue("GoogleRefreshToken"), Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))), ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")), }; return new UserCredential(flow, userId, token); } } 

Add this to Application_Start () in Global.asax

  AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; 
0
Dec 25 '15 at 13:16
source share



All Articles