0

Kann mir jemand helfen, die Google Docs API-Refresh-Token zum ersten Mal in Asp. Net MVC. Ich habe Client-ID und Client-Secrete, woher soll ich das Refresh-Token und weiter von Refresh-Token, wie bekomme ich das Zugriffstoken, um auf die Google API für Laufwerk zugreifen.Holen Sie sich die Google Docs API Refresh-Token und Zugriffstoken mit Asp.Net MVC

+0

Welche Version der Google Docs API haben Sie untersucht? – DaImTo

+0

Ich benutzte Google API v3. –

+0

Ich nehme immer noch an, du meinst Google Drive API als Google Docs API ist eigentlich kein Ding – DaImTo

Antwort

2

Sie haben nicht viel mit dem Beispielcode für die Drive API V3 getan, aber sie haben. Ich würde nicht alle diese Bereiche verwenden, die auswählen, welche Sie benötigen, ist dieser Code vorgeneriert.

NuGet Paket

PM>Install-Package Google.Apis.Drive.v3

/// <summary> 
    /// This method requests Authentication from a user using Oauth2. 
    /// Credentials are stored in System.Environment.SpecialFolder.Personal 
    /// Documentation https://developers.google.com/accounts/docs/OAuth2 
    /// </summary> 
    /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param> 
    /// <param name="userName">Identifying string for the user who is being authentcated.</param> 
    /// <returns>DriveService used to make requests against the Drive API</returns> 
    public static DriveService AuthenticateOauth(string clientSecretJson, string userName) 
    { 
     try 
     { 
      if (string.IsNullOrEmpty(userName)) 
       throw new Exception("userName is required."); 
      if (!File.Exists(clientSecretJson)) 
       throw new Exception("clientSecretJson file does not exist."); 

      // 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[] { DriveService.Scope.Drive,     // View and manage the files in your Google Drive 
              DriveService.Scope.DriveAppdata,   // View and manage its own configuration data in your Google Drive 
              DriveService.Scope.DriveFile,    // View and manage Google Drive files and folders that you have opened or created with this app 
              DriveService.Scope.DriveMetadata,   // View and manage metadata of files in your Google Drive 
              DriveService.Scope.DriveMetadataReadonly, // View metadata for files in your Google Drive 
              DriveService.Scope.DrivePhotosReadonly,  // View the photos, videos and albums in your Google Photos 
              DriveService.Scope.DriveReadonly,   // View the files in your Google Drive 
              DriveService.Scope.DriveScripts};   // Modify your Google Apps Script scripts' behavior 
      UserCredential credential; 
      using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read)) 
      { 
       string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); 
       credPath = Path.Combine(credPath, ".credentials/apiName"); 

       // Requesting Authentication or loading previously stored authentication for userName 
       credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, 
                     scopes, 
                     userName, 
                     CancellationToken.None, 
                     new FileDataStore(credPath, true)).Result; 
      } 

      // Create Drive API service. 
      return new DriveService(new BaseClientService.Initializer() 
       { 
        HttpClientInitializer = credential, 
        ApplicationName = "Drive Authentication Sample", 
       }); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message); 
      throw new Exception("CreateOauth2DriveFailed", ex); 
     } 
    } 

Dienstkonto Json Schlüsseldatei nicht die p12

/// <summary> 
    /// Authenticating to Google using a Service account 
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount 
    /// 
    /// Note: Not all APIs support service accounts I cant garentee this will work. If you find an api that doesnt support service accoutns contact me 
    ///  me at www.daimto.com and I will remove it from auto genration of this APIs sample project. 
    /// </summary> 
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> 
    /// <param name="serviceAccountCredentialFilePath">Location of the Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param> 
    /// <returns>DriveService used to make requests against the Drive API</returns> 
    public static DriveService AuthenticateServiceAccount(string serviceAccountCredentialFilePath) 
    { 
     try 
     { 
      if (string.IsNullOrEmpty(serviceAccountCredentialFilePath)) 
       throw new Exception("Path to the .JSon service account credentials file is required."); 
      if (!File.Exists(serviceAccountCredentialFilePath)) 
       throw new Exception("The service account credentials .JSon file does not exist at:" + serviceAccountCredentialFilePath); 

      // 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[] { DriveService.Scope.Drive,     // View and manage the files in your Google Drive 
              DriveService.Scope.DriveAppdata,   // View and manage its own configuration data in your Google Drive 
              DriveService.Scope.DriveFile,    // View and manage Google Drive files and folders that you have opened or created with this app 
              DriveService.Scope.DriveMetadata,   // View and manage metadata of files in your Google Drive 
              DriveService.Scope.DriveMetadataReadonly, // View metadata for files in your Google Drive 
              DriveService.Scope.DrivePhotosReadonly,  // View the photos, videos and albums in your Google Photos 
              DriveService.Scope.DriveReadonly,   // View the files in your Google Drive 
              DriveService.Scope.DriveScripts};   // Modify your Google Apps Script scripts' behavior 
      Stream stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); 
      var credential = GoogleCredential.FromStream(stream).CreateScoped(scopes); 

      // Create the Drive service. 
      return new DriveService(new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = "Drive Authentication Sample", 
      }); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Create service account DriveService failed" + ex.Message); 
      throw new Exception("CreateServiceAccountDriveServiceFailed", ex); 
     } 
    } 

Lassen Sie mich wissen, wenn Sie etwas anderes, ich habe Teilbeispielprojekt gebaut.

+0

Vielen Dank DalmTo. Ich habe den UserCredential und DriveService erfolgreich erhalten. Können Sie mir bitte mitteilen, dass es möglich ist, dass mein Seitenbesucher Dateien auf mein Google Drive hochladen kann und ich die oauth im Hintergrund autorisieren werde, d. Wie kann ich das erreichen? –

+0

Wenn Sie die Personen in Ihr Konto hochladen möchten. Sie sollten in Erwägung ziehen, ein Dienstkonto anstelle von Oauth2 zu verwenden. Dann können Sie den Ordner auf Ihrem Laufwerkskonto mit dem Dienstkonto teilen. Dienstkonten sind eine Art Dummy-Benutzer, die das Dienstkonto in den Laufwerksordner hochladen kann. Denken Sie daran, dass das Dienstkonto die Berechtigungen für die Datei aktualisieren muss, um Ihnen nach dem Hochladen Berechtigungen zu gewähren, andernfalls haben Sie eine Datei auf Ihrem Laufwerkskonto Sie haben keine Zugriffsberechtigungen. – DaImTo

+0

bevor Sie fragen, haben Sie mehr Code für Service Account Auth. und Mein Tutorial zu Serviceaccounts, damit Sie das Konzept verstehen http://www.daimto.com/google-developer-console-service-account/ – DaImTo

Verwandte Themen