我正在尝试使用 Windows 应用程序或服务中的 Google 驱动器。
我不需要 Web App、MVC 等。
系统必须自动运行,没有任何用户入侵,所以我创建了服务帐户并获取证书和电子邮件。
而且,当然,下载了最后一个客户端库 - http://code.google.com/p/google-api-dotnet-client/
我在文档中构建服务对象:
private const string SERVICE_ACCOUNT_EMAIL = "xxx@developer.gserviceaccount.com";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"xxx-privatekey.p12";
/// <summary>
/// Build a Drive service object authorized with the service account.
/// </summary>
/// <returns>Drive service object.</returns>
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 ( ),
ServiceAccountUser = "myemail@gmail.com",
};
var auth = new OAuth2Authenticator<AssertionFlowClient> ( provider, AssertionFlowClient.GetState );
return new DriveService ( auth );
} // BuildService
然后我这样做:
service = BuildService ( );
FilesResource.InsertMediaUpload request = service.Files.Insert ( body, stream, mimeType );
request.Upload ( );
File file = request.ResponseBody;
我在上传方法中遇到异常 - 未知对象标识符 (OID)。我找到了引发此异常的命令:
字符串签名 = UnpaddedUrlSafeBase64Encode (Key.SignData (Encoding.ASCII.GetBytes(assertion.ToString()), "SHA256"));
这在 Google.Apis.Authentication.OAuth2.dll、文件 AssertionflowClient.cs、方法 GenerateMessage 中。
但谷歌证书只有 SHA1 算法。从证书信息窗口可以看出这一点: X509Certificate2UI.DisplayCertificate ( certificate ); 或从窗户。
我尝试使用 SHA1: String signature = UnpaddedUrlSafeBase64Encode ( Key.SignData ( Encoding.ASCII.GetBytes ( assertion.ToString ( ) ), "SHA1" ) );
之后这个异常消失了,但我得到了 HTTP 错误 400(无效请求)。如何使用服务帐户使用 Google 驱动器?