2015-09-23 64 views
0

我正在尝试构建一个应用程序,该应用程序可以读写私人Google电子表格。为此,我需要使用Google OAuth2.0。如何使用刷新令牌为Google SpreadsheetsService获取新的访问令牌

我的问题是我1小时后失去访问权限。我认为这意味着刷新令牌未被正确使用。这是我处理验证的代码:

public static SpreadsheetsService AuthenticateOauth(string clientId, string clientSecret, string userName) 
    { 

     string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents 
             DriveService.Scope.DriveAppdata, 
             DriveService.Scope.DriveAppsReadonly, 
             DriveService.Scope.DriveFile, 
             DriveService.Scope.DriveMetadataReadonly, 
             DriveService.Scope.DriveReadonly, 
             "https://spreadsheets.google.com/feeds", 
             "https://docs.google.com/feeds" 

     }; 


     try 
     { 
      // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% 
      UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } 
                         , scopes 
                         , userName 
                         , CancellationToken.None 
                         , new FileDataStore("MY.APP.Auth.Store")).Result; 

      SpreadsheetsService service = new SpreadsheetsService(My App"); 
      var requestFactory = new GDataRequestFactory("My App"); 

      requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken)); 
      service.RequestFactory = requestFactory; 

      return service; 
     } 
     catch (Exception ex) 
     { 


      Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException); 
      return null; 

     } 

    } 

我该如何着手使刷新令牌正确使用?

+0

因为你在混合两个不同的api系统。如果它自己的电子表格和你自己控制我有一个服务帐户的例子,可能有助于http://www.daimto.com/google-sheets-with-c/我没有得到周围的工作与Oauth2然而。 – DaImTo

+0

感谢@DaImTo,不幸的是我需要使用OAuth2才能使用它。感谢您的教程,顺便说一句,他们真的是一个巨大的帮助:-) –

+0

好吧,这里是一个黑客:你也使用驱动器。如果您创建驱动服务并发送虚拟请求。如果需要,它会自动提取新的访问令牌,然后您可以将其添加到您的工作表请求中。 – DaImTo

回答

1

您正在使用当前的Google .NET客户端库进行身份验证。 当您创建服务时,通常会在需要时自动刷新您的访问令牌。但是,您正在向旧Gdata库发送访问令牌,该库不会自动刷新它。

如果您创建驱动器服务并每小时运行一次虚拟请求,它将在需要时为您刷新访问令牌。

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

// Dummy request example: 
FilesResource.ListRequest list = service.Files.List(); 
list.MaxResults = 1; 
list.Q = "title=dummysearch"; 
FileList dummyFeed = list.Execute(); 
// End of Dummy request 
相关问题