如何在 Google 分析报告 API 中使用 OAuth2 进行身份验证?

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

我在 Windows 控制台应用程序中使用 C#.NET 进行编码,并尝试下载 Google Analytics 指标数据。我已经安装了 Google.Apis.AnalyticsReporting.v4 NuGet 库包,它引入了 Google.Apis、Google.Apis.Auth 和 Google.Apis.Core 作为依赖项。

我的问题是,我需要使用 Google.Apis.AnalyticsReporting.v4 或 Google.Apis.Auth NuGet 库包中的哪些特定方法来使用 OAuth2 进行身份验证?我有凭据。我只需要知道如何提交它们。

这在一定程度上取决于您要访问谁的数据,如果它是用户数据,那么您将使用以下内容

确保在 google 开发者控制台中创建桌面凭据

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);
            }

如果您想访问单个帐户并对其进行控制,那么您可以使用服务帐户

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