Search code examples
c#oauth-2.0google-apigoogle-analytics-apigoogle-api-dotnet-client

How do I authenticate using OAuth2 in the Google Analytics Reporting API?


I'm coding in C#.NET, in a Windows console application, and trying to download Google Analytics metrics data. I've installed the Google.Apis.AnalyticsReporting.v4 NuGet library package, and it brought in Google.Apis, Google.Apis.Auth, and Google.Apis.Core as dependencies.

My question is, what specific methods in the Google.Apis.AnalyticsReporting.v4 or Google.Apis.Auth NuGet library packages do I need to use to authenticate using OAuth2? I have the credentials. I just need to know how to submit them.


Solution

  • this depends a little on whos data you are going to be accessing if its a users data then you would use the following

    make sure to create desktop credetinals in google developer console

    private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
            {
                try
                {
                    if (string.IsNullOrEmpty(userName))
                        throw new ArgumentNullException("userName");
                    if (string.IsNullOrEmpty(clientSecretJson))
                        throw new ArgumentNullException("clientSecretJson");
                    if (!File.Exists(clientSecretJson))
                        throw new Exception("clientSecretJson file does not exist.");
    
                    // These are the scopes of permissions you need. It is best to request only what you need and not all of them               
                    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
                        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                                 scopes,
                                                                                 userName,
                                                                                 CancellationToken.None,
                                                                                 new FileDataStore(credPath, true)).Result;
    
                        credential.GetAccessTokenForRequestAsync();
                        return credential;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Get user credentials failed.", ex);
                }
    

    If you want to access a single account and you cotrol that then you could use service acount

    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }