Comment fournir des informations d’identification par programme pour utiliser Google Drive api en c # ou vb.net?

J’ai créé un programme qui utilise Google Drive API pour lire les données d’un fichier sur Google Drive.

la première fois que vous exécutez l’application, un navigateur Web s’ouvre et vous invite à vous connecter avec un compte Google Drive.

Je souhaite fournir à l’application le nom d’utilisateur et le mot de passe de manière à ce qu’elle obtienne automatiquement les informations d’identification afin que les utilisateurs n’aient pas besoin de connaître le nom d’utilisateur et le mot de passe de mon compte Google Drive.

voici le code dans vb.net:

Dim credential As UserCredential Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read) Dim credPath As Ssortingng = 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 

voici le code en c #:

  UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { ssortingng 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 files = listRequest.Execute() .Files; 

Malheureusement, vous ne pouvez pas intégrer un identifiant et un mot de passe comme celui-ci. J’ai une autre option pour vous.

On dirait que vous essayez d’autoriser les utilisateurs à accéder à votre compte Google Drive personnel. Dans ce cas, vous devriez utiliser un compte de service et pas Oauth2. Oauth2 requirejs une interaction de l’utilisateur sous la forme d’une page Web pour accorder à une application l’access au compte Google Drive de l’utilisateur. Les comptes de service sont préalablement autorisés par le développeur en arrière-plan.

Pensez à un compte de service en tant qu’utilisateur factice. Vous pouvez lui accorder l’access à votre compte Google Drive en partageant un dossier de votre lecteur Google avec l’adresse e-mail du compte de service.

Voici un exemple de code pour l’authentification auprès d’un compte de service.

 ///  /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount ///  /// From Google Developer console https://console.developers.google.com /// Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com /// AnalyticsService used to make requests against the Analytics API public static DriveService AuthenticateServiceAccount(ssortingng serviceAccountEmail, ssortingng serviceAccountCredentialFilePath) { try { if (ssortingng.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 (ssortingng.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 ssortingng[] scopes = new ssortingng[] { 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 certificatee = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificatee)); // 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); } } } 

Usage:

  var service = AuthenticateServiceAccount("1046123799103-6v9cj8jbub068jgmss54m9gkuk4q2qu8@developer.gserviceaccount.com", @"C:\Users\linda_l\Documents\Diamto Test Everything Project\ServiceAccountTest\Diamto Test Everything Project-145ed16d5d47.json"); 

Code extrait de mon exemple de projet Google Drive non officiel serviceaccount.cs. J’ai également un article qui va plus loin dans les comptes de service Compte de service de la console Google Developer