Google 驱动器访问:至少应设置一个客户端密码(已安装或 Web)

Google Drive Access: At least one client secrets (Installed or Web) should be set

我们已经测试了 Google 驱动器(用于控制台应用程序)的演示代码并且一切正常,之后我们正在尝试对目前托管在本地主机上的 Web 应用程序实施相同的代码。该应用程序给了我们这个例外:

An exception of type 'System.InvalidOperationException' occurred in Google.Apis.Auth.dll but was not handled in user code Additional information: At least one client secrets (Installed or Web) should be set

我们正在尝试 运行 的代码是这样的:

UserCredential credential;
        GoogleClientSecrets s= new GoogleClientSecrets();
        s.Secrets.ClientId="xxxxxxxxxx-xxxxxxxx.apps.googleusercontent.com";
        s.Secrets.ClientSecret="yyyyyyyyyyyyyyyyyyyyy";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(s.Secrets,Scopes,"user",CancellationToken.None,null).Result;
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
            //ApplicationName = ApplicationName,
        });

在此之前我们已经放置了刷新令牌来获取访问令牌。我们也不知道如何处理这个存储在字符串变量中的访问令牌。

我们试图让它在无人值守的情况下访问,我们使用 google playground 来获取第一个刷新令牌。

请帮助我们,过去 7 天我们一直在尝试完成它,但没有成功。

服务帐户代码:

string[] scopes = new string[] {DriveService.Scope.Drive}; // Full access
var keyFilePath = @"c:\file.p12" ;    // Downloaded from https://console.developers.google.com 
var serviceAccountEmail = "xx@developer.gserviceaccount.com";  // found https://console.developers.google.com 


//loading the Key file 
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); 
var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { 
Scopes = scopes}.FromCertificate(certificate)); 

Google Drive Authentication C# 中提取的代码,其中还包含一个使用 Oauth2

的示例

上传文件

/// <summary>
        /// Uploads a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_uploadFile">path to the file to upload</param>
        /// <param name="_parent">Collection of parent folders which contain this file. 
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file 
        ///          If the upload fails returns null</returns>
        public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {

            if (System.IO.File.Exists(_uploadFile))
            {
                File body = new File();
                body.Title = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File uploaded by Diamto Drive Sample";
                body.MimeType = GetMimeType(_uploadFile);
                body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

                // File's content.
                byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                try
                {
                    FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
                    //request.Convert = true;   // uncomment this line if you want files to be converted to Drive format
                    request.Upload();
                    return request.ResponseBody;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return null;
                }
            }
            else {
                Console.WriteLine("File does not exist: " + _uploadFile);
                return null;
            }           

        }

DaimtoGoogleDriveHelper.cs

中窃取的代码

提示:

使用服务帐户要记住的一点是,它不是您,而是一个虚拟用户帐户。服务帐户有自己的 google 驱动器帐户,因此将文件上传到它会上传到它的帐户而不是你的帐户。您可以做的是获取服务帐户电子邮件地址,将其作为用户添加到您的个人 google 驱动器帐户中的文件夹中,并授予其写入权限。这将允许服务帐户将文件上传到您的个人 google 驱动器帐户。请记住在上传后修补文件,授予自己对文件的权限,否则文件的所有者将是服务帐户。当前 Google 驱动器 api 中存在一个错误,您必须在上传文件后修补文件的权限,您在上传文件时无法执行此操作,这是一个两步过程。 (在那里做过)

Google 可以在 GitHub

上找到驱动示例项目