google drive api v2 получи ошибку аутентификации - PullRequest
0 голосов
/ 03 июля 2018

я пользуюсь языком c #, сервис предоставляет мне исключение

"не удалось запустить браузер с https //accounts.google.com/o/oauth2/v2/auth"

шаги, за которыми я следовал:

  1. Включение службы API Google Drive от разработчика консоли Google
  2. Создание идентификатора клиента, секрета клиента (я пробовал два типа идентификатора клиента OAuth {Веб-приложение и прочее} два типа дают мне одно и то же исключение

Мой код:

    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;
    }

1 Ответ

0 голосов
/ 03 июля 2018

Вы используете код для установленных приложений. Код пытается открыть новое окно браузера для согласия на сервере, а не в браузере пользователя.

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 Диске, которую вы можете загрузить. Вы не можете использовать веб-просмотр, чтобы увидеть, что находится на этой учетной записи. Вам нужно будет создать учетные данные учетной записи службы, а не учетные данные 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

...