0

Я пытаюсь загрузить файл с Google Диска с помощью .NET API.Истек срок доступа, но мы не можем его обновить.

private UserCredential _credential; 

    protected void Authorize() 
    { 
     var scopes = new[] {DriveService.Scope.DriveReadonly}; 

     using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) 
     { 
      var credentialPath = @"App_Data\credential"; 

      _credential = 
       new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer 
       { 
        ClientSecrets = GoogleClientSecrets.Load(stream).Secrets, 
        Scopes = scopes 
       }), Environment.UserName, new TokenResponse()); 

      // I tried both ways, both result the same exception 
      //_credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, Environment.UserName, CancellationToken.None).Result; 
     } 
    } 

    public Download SaveAsDownload(string fileId) 
    { 
     if(_credential == null) 
      Authorize(); 

     var service = new DriveService(new BaseClientService.Initializer() 
     { 
      ApiKey = ApiKey, 
      HttpClientInitializer = _credential 
     }); 

     var getRequest = service.Files.Get(fileId); 
     var file = getRequest.Execute(); // When I call this I get the exception 

     return null; 
    } 

Каждый раз, когда я пытаюсь сделать это, я получаю «Маркер доступа истек, но мы не можем обновить это» исключение. Единственный ответ, который я нашел, - попробовать другой способ аутентификации, но я попробовал оба, и оба результата имеют одинаковое исключение. Я пробовал как версии версии SD2, так и версии v3.

ответ

0

Пожалуйста, удалите

ApiKey = ApiKey,

от вашего DriveService. Вы путаете библиотеку клиентов, пытаясь использовать открытый ключ api, когда он должен использовать ваши учетные данные OAuth.

видел это пару раз отправил вопрос о библиотеке Creating service with credentials and ApiKey

Update также может быть проблемой остроумие код

Мой диск Auth код:

/// <summary> 
    /// This method requests Authentcation 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.DriveReadonly};   // 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); 
     } 
    } 
+0

не помогло, все те же исключения – micnyk

+0

Ваш код швов странный. попробуйте этот пример – DaImTo

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