3

Я создал программу, которая использует google drive api для чтения данных из файла на Google Диске.Как предоставить учетные данные программным образом для использования google drive api в C# или vb.net?

При первом запуске приложения открывается веб-браузер с просьбой войти в систему с учетной записью Google.

Я хочу предоставить приложению имя пользователя и пароль, чтобы автоматически получать учетные данные, чтобы пользователям не нужно было знать имя пользователя и пароль моей учетной записи Google.

здесь код в vb.net:

Dim credential As UserCredential 

    Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read) 
     Dim credPath As String = System.Environment.GetFolderPath(
      System.Environment.SpecialFolder.Personal) 
     credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json") 

     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
     GoogleClientSecrets.Load(stream).Secrets, 
     Scopes, 
     "user", 
     CancellationToken.None, 
     New FileDataStore(credPath, True)).Result 
     'Console.WriteLine("Credential file saved to: " + credPath) 
    End Using 

    //I want to provide the username and password in the app so that it doesn't open a web browser asking for them 

    ' Create Drive API service. 
    Dim initializer = New BaseClientService.Initializer 
    initializer.HttpClientInitializer = credential 
    initializer.ApplicationName = ApplicationName 
    Dim service = New DriveService(initializer) 

    ' Define parameters of request. 
    Dim listRequest As FilesResource.ListRequest = service.Files.List() 
    listRequest.PageSize = 10 
    listRequest.Fields = "nextPageToken, files(id, name)" 

    ' List files. 
    Dim files As IList(Of Google.Apis.Drive.v3.Data.File) = listRequest.Execute().Files 

здесь код в C#:

 UserCredential credential; 

     using (var stream = 
      new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) 
     { 
      string credPath = System.Environment.GetFolderPath(
       System.Environment.SpecialFolder.Personal); 
      credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json"); 

      credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
       GoogleClientSecrets.Load(stream).Secrets, 
       Scopes, 
       "user", 
       CancellationToken.None, 
       new FileDataStore(credPath, true)).Result; 
      //Console.WriteLine("Credential file saved to: " + credPath); 
     } 

     //I want to provide the username and password in the app so that it doesn't open a web browser asking for them 

     // Create Drive API service. 
     var service = new DriveService(new BaseClientService.Initializer() 
     { 
      HttpClientInitializer = credential, 
      ApplicationName = ApplicationName, 
     }); 

     // Define parameters of request. 
     FilesResource.ListRequest listRequest = service.Files.List(); 
     listRequest.PageSize = 10; 
     listRequest.Fields = "nextPageToken, files(id, name)"; 

     // List files. 
     IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() 
      .Files; 

ответ

4

К сожалению, вы не можете вставить логин и пароль, как это. У меня есть другой вариант для вас.

Похоже, вы пытаетесь разрешить пользователям доступ к вашей личной учетной записи Google Диска. В этом случае вы должны использовать учетную запись службы и не Oauth2. Oauth2 требует взаимодействия пользователя в форме веб-страницы, чтобы предоставить приложение доступ к учетной записи Google для собственных пользователей. Хотя учетные записи служб предварительно разрешены разработчиком в фоновом режиме.

Подумайте об учетной записи службы в качестве фиктивного пользователя. Вы можете предоставить ему доступ к своей учетной записи Google Диска, поделившись папкой на вашем диске Google с адресом электронной почты учетных записей службы.

Вот пример кода для аутентификации с учетной записью службы.

/// <summary> 
    /// Authenticating to Google using a Service account 
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount 
    /// </summary> 
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> 
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param> 
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns> 
    public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath) 
    { 
     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."); 

      // These are the scopes of permissions you need. It is best to request only what you need and not all of them 
      string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics };    // View your Google Analytics data 

      // 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) 
     { 
      Console.WriteLine("Create service account DriveService failed" + ex.Message); 
      throw new Exception("CreateServiceAccountDriveFailed", ex); 
     } 
    } 
} 

Использование:

var service = AuthenticateServiceAccount("[email protected]eaccount.com", @"C:\Users\linda_l\Documents\Diamto Test Everything Project\ServiceAccountTest\Diamto Test Everything Project-145ed16d5d47.json"); 

код вырванного из моего неофициального Google диск образца проекта serviceaccount.cs У меня также есть статья, которая идет вглубь службу счетов Google Developer console service account

+1

вы можете привести пример вызова этого метода потому что я думаю, что я предоставляю неправильное значение serviceAccountCredentialFilePath. –

+0

Я использую json-файл, однако он должен работать с файлом ключа .p12. Помните, что это должны быть учетные данные учетной записи службы, а не файл учетных данных, который вы создали ранее для Oauth2. есть разница. – DaImTo

+0

Я использую файл client_secret.json, который я загрузил с консоли. Можете ли вы представить пример. –

 Смежные вопросы

  • Нет связанных вопросов^_^