我尝试使用代表另一个用户的服务帐户创建 DriveService。
我从这里找到的谷歌文档复制了这段代码https://developers.google.com/drive/delegation
static DriveService BuildService() {
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DriveService.Scopes.Drive.GetStringValue(),
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
return new DriveService(auth);
}
但我在尝试构建项目时收到此警告:
警告 4 'Google.Apis.Authentication.OAuth2.DotNetOpenAuth.AssertionFlowClient' 已过时:'AssertionFlowClient 不再受支持,它将在 1.7.0-beta 中删除。考虑使用新的 Google.Apis.Auth NuGet 包中的 ServiceAccountCredential。
我也收到此错误:
错误 11 参数 1:无法从“Google.Apis.Authentication.OAuth2.OAuth2Authenticator”转换为“Google.Apis.Services.BaseClientService.Initializer”
然后我用谷歌搜索 ServiceAccountCredential 并最终得到了这个代码(来自这个页面: https ://code.google.com/p/google-api-dotnet-client/wiki/OAuth2#Service_Accounts )
static DriveService BuildService() {
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
User = "someone@mydomain.mygbiz.com",
Scopes = new[] { DriveService.Scope.DriveFile }
}.FromCertificate(certificate));
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
return service;
}
当我尝试构建此代码时,它似乎一切都很好,但是当我运行它时,我收到以下错误。
mscorlib.dll 中出现了“System.Security.Cryptography.CryptographicException”类型的第一次机会异常
附加信息:Det går inte att hitta det begärda objektet。(翻译:找不到请求的对象)
如果有这个异常的处理程序,程序可以安全地继续。
错误发生在这一行:
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
有人有想法么?
2013 年 10 月 31 日更新我已经尝试过这段代码:
{
Console.WriteLine("Drive API - Service Account");
Console.WriteLine("==========================");
String serviceAccountEmail = "<some email>@developer.gserviceaccount.com";
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = "<someuser>@<mydomain>.mygbiz.com",
Scopes = new[] { DriveService.Scope.Drive }
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "DrvMgr",
});
Console.WriteLine("Executing listing");
FileList UserFiles = service.Files.List().Execute();
我收到此错误消息:
Google.Apis.dll 中出现“Google.Apis.Auth.OAuth2.Responses.TokenResponseException”类型的未处理异常
附加信息:错误:“access_denied”,描述:“”,Uri:“”