不能使用c# /. net中的服务帐户在Google drive中授权

本文关键字:Google 授权 drive 服务 net 不能 | 更新日期: 2023-09-27 18:03:57

我正在尝试从Windows应用程序或服务中使用谷歌驱动器。

我不需要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(密钥。getbytes(断言。ToString (), "SHA256");

在Google.Apis.Authentication.OAuth2.dll中,文件AssertionflowClient.cs,方法generatemmessage .

但是Google证书只有SHA1算法。从证书信息窗口X509Certificate2UI中可以看出这一点。DisplayCertificate(证书);或者从windows。

我尝试使用SHA1:字符串签名= UnpaddedUrlSafeBase64Encode(密钥。getbytes(断言。ToString (), "SHA1"));

之后,这个异常消失了,但我得到HTTP错误400(无效请求)。我怎么能与谷歌驱动器与服务帐户工作?

不能使用c# /. net中的服务帐户在Google drive中授权

在你的代码中删除

ServiceAccountUser = "myemail@gmail.com",

或转到google apps域的管理控制台并授权您的服务帐户。

您是否按照OAuth2服务帐户页面的说明生成了新密钥?

你可以尝试其他的服务请求吗,比如插入没有媒体上传的请求(InsertRequest插入(google . api . drive .v1. data . data)。

文件主体)-如果其他方法也不适合你,请告诉我。

请注意,在服务帐户文档中说:"服务帐户依赖于RSA SHA256算法和JWT令牌格式"。这是支持的算法,而不是SHA1。