gpt4 book ai didi

c# - 在 C# 中使用 OAuth2 通过 Google API 进行身份验证

转载 作者:太空宇宙 更新时间:2023-11-03 12:31:54 27 4
gpt4 key购买 nike

我创建了一个控制台应用程序,它使用 OAuth2 通过 GoogleAnalyticsApiV4 进行身份验证以查询一些数据。该应用程序按预期工作,但我们希望使该过程自动化,以便可以安排该应用程序每天运行一次。这里的问题是应用程序将托管在 azure 上,用户无法接受应用程序第一次运行时在浏览器中弹出的 google 身份验证请求。

以下在线帖子和谷歌文档是我当前的身份验证解决方案

     try
{
var credential = GetCredential().Result;

using (var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
///// Query some data/////
}



static async Task<UserCredential> GetCredential()
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
string loginEmailAddress = ConfigurationManager.AppSettings["GoogleUsername"];
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { AnalyticsReportingService.Scope.Analytics },
loginEmailAddress, CancellationToken.None,
new FileDataStore("GoogleAnalyticsApiConsole"));
}
}

只要用户可以输入凭据并接受身份验证请求,此解决方案就可以很好地通过 Google 进行身份验证。不幸的是,一旦应用程序移动到另一台计算机,它就需要重新进行身份验证,并且用户需要再次输入凭据并接受请求。

我一直在寻找一种方法将用户带出进程,以便应用程序可以在 azure 上运行,但还没有找到任何关于如何在 c# 中执行此操作的明确信息。

请有人描述我如何在没有用户的情况下通过谷歌验证我的应用程序,或者为我指出准确涵盖该过程的文档的方向。

如果有帮助或示例,我们将不胜感激。

最佳答案

您有几个选择。

这是您有权访问的帐户吗?如果是,那么您可以使用服务帐户。服务帐户是预先授权的,您获取服务帐户电子邮件地址并将其添加为帐户级别的 Google 分析管理员中的用户,并且只要该帐户有效,该服务帐户就可以访问该帐户。不需要弹出窗口。我有一些关于如何使用服务帐户进行身份验证的示例代码 here

/// <summary>
/// Authenticating to Google using a Service account
/// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// </summary>
/// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
/// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
/// <returns>AnalyticsService used to make requests against the Analytics API</returns>
public static AnalyticsReportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath)
{
try
{
if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(serviceAccountCredentialFilePath))
throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
if (string.IsNullOrEmpty(serviceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");

// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics }; // View your Google Analytics data

// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}

// Create the Analytics service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AnalyticsReporting Service account Authentication Sample",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file

var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));

// Create the AnalyticsReporting service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AnalyticsReporting Authentication Sample",
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}

}
catch (Exception ex)
{
Console.WriteLine("Create service account AnalyticsReportingService failed" + ex.Message);
throw new Exception("CreateServiceAccountAnalyticsReportingFailed", ex);
}
}

如果这不是你能做的事情。然后您应该意识到 filedatastore() 默认情况下将您的凭据存储在 %appData% 中,您只需将该文件与代码一起复制到新服务器上即可。

您还可以使用以下代码将位置移动到 %appData% 以外的位置:

new FileDataStore(@"c:\datastore",true)     

我有一个关于 filedatastore 如何工作的教程。在这里File datastore demystified

向 Google Analytics 预授权服务帐户。 Google 分析网站的管理部分。授予它读取权限应该就足够了。

enter image description here

关于c# - 在 C# 中使用 OAuth2 通过 Google API 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42437474/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com