首页 > 解决方案 > google drive api v2 让我验证错误

问题描述

我正在使用 c# 语言服务让我例外

“无法使用 https //accounts.google.com/o/oauth2/v2/auth 启动浏览器”

我遵循的步骤:

  1. 从谷歌控制台开发者启用谷歌驱动API服务
  2. 生成客户端 ID,客户端密码(我尝试了两种类型的 OAuth 客户端 ID 类型 {Web 应用程序和其他},这两种类型让我遇到相同的异常

我的代码是:

    public File InsertFile(byte[] byteArray)
    {
        // File's metadata
        File body = new File();
        body.Title = "my title";
        body.Description = "my description";
        body.MimeType = "image/jpg";

        // File's content.
        System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

        try
        {

            var credential = Authentication();

            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = string.Format("{0} elfeedback-project", System.Diagnostics.Process.GetCurrentProcess().ProcessName),
            });

            FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/jpg");
            request.UploadAsync();

            File file = request.ResponseBody;

            return file;
        }
        catch (Exception ex)
        {
            return null;
        }
    }`

身份验证获取异常:

    `public UserCredential Authentication()
    {
        string[] scopes = { DriveService.Scope.Drive,
                   DriveService.Scope.DriveFile,
        };

        UserCredential credential;
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
            ClientId = "my client id",
            ClientSecret = "my client secret"
        },
        scopes,
        "myGmail Account that authenticated (client id ,client secret)",
        CancellationToken.None,
        new FileDataStore("Drive.Auth.Store")).Result;

        return credential;
    }

标签: c#google-apigoogle-drive-apigoogle-api-dotnet-clientservice-accounts

解决方案


您正在使用已安装应用程序的代码。该代码试图在服务器而不是用户浏览器上打开一个新的浏览器窗口以获得同意。

new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = "PUT_CLIENT_ID_HERE",
                    ClientSecret = "PUT_CLIENT_SECRET_HERE"
                },
                Scopes = new[] { DriveService.Scope.Drive },
                DataStore = new FileDataStore("Drive.Api.Auth.Store")
            });

更新

如果您想上传到您控制的帐户,那么您应该考虑使用服务帐户。服务帐户是虚拟用户,他们有自己的 Google Drive 帐户,您可以上传到该帐户。您不能使用网络视图查看此帐户的内容。您将需要创建服务帐户凭据而不是 OAuth 凭据。

public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Drive service.
                    return new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountDriveFailed", ex);
            }
        }
    }

ServiceAccount.cs中提取的代码


推荐阅读