如何使用谷歌云平台服务帐户和密钥文件在.NET中建立到谷歌存储的oauth-2连接?可用的示例和文档没有涉及服务帐户,并且API令人困惑,并且似乎经常更改,这使得现有的文档令人怀疑。一个有效的代码示例是最好的,包括重要的API命名空间和版本。
发布于 2016-07-27 02:45:13
不幸的是,在将GOOGLE_APPLICATION_CREDENTIALS设置为指向下载的JSON密钥之后,Cloud Storage JSON API documentation中的代码示例仅涵盖了使用应用程序默认凭据。
但是,documentation for the Google API Client Library for .NET中有一个示例,用于使用带有导出的P12密钥的服务帐户,您可以使用它来适配云存储文档中给出的CreateStorageClient()方法:
public StorageService CreateStorageClient()
{
String serviceAccountEmail = "SERVICE_ACCOUNT_EMAIL_HERE";
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { StorageService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
var serviceInitializer = new BaseClientService.Initializer()
{
ApplicationName = "Storage Sample",
HttpClientInitializer = credential
};
return new StorageService(serviceInitializer);
}基于API docs的直接使用JSON键的相同方法
public StorageService CreateStorageClient()
{
GoogleCredential credential;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(StorageService.Scope.DevstorageFullControl);
}
var serviceInitializer = new BaseClientService.Initializer()
{
ApplicationName = "Storage Sample",
HttpClientInitializer = credential
};
return new StorageService(serviceInitializer);
}请注意,我还没有测试这些,因为我目前还没有设置.NET开发环境,但它应该给出了它是如何工作的大体概念。我将请求对云存储文档进行更新,以添加使用JSON密钥的示例。
https://stackoverflow.com/questions/38359675
复制相似问题