访问令牌过期后如何继续上传?

时间:2013-01-31 14:23:20

标签: .net google-drive-api google-oauth google-api-dotnet-client

我在.net中有一个桌面应用程序可以将文件上传到Google云端硬盘。要授权的应用程序使用服务帐户。问题在于大文件(+ 300MB)。上传1小时后,应用程序会引发错误消息:

  

凭据无效

问题是访问令牌已过期,我不知道如何刷新凭据。

创建DriveService的功能是:

Public Function getAuthenticator() As OAuth2Authenticator(Of AssertionFlowClient)
      Dim SERVICE_ACCOUNT_EMAIL As String = <email>
      Dim SERVICE_ACCOUNT_PKCS12_FILE_PATH As String = <pathFile>
      Dim certificate As X509Certificate2 = New X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, <secret>, X509KeyStorageFlags.Exportable)
      Dim provider = New AssertionFlowClient(GoogleAuthenticationServer.Description, certificate) With {.ServiceAccountId = SERVICE_ACCOUNT_EMAIL, .Scope = DriveService.Scopes.Drive.GetStringValue}
      Dim auth = New OAuth2Authenticator(Of AssertionFlowClient)(provider, AddressOf AssertionFlowClient.GetState)

      auth.LoadAccessToken()
      Return auth
End Function 

Public Function getService() As DriveService
    Return New DriveService(getAuthenticator())
End Function

上传的功能是:

Public Function upload(pathFile As String, fileName As String) As File
       Dim service = getService()
       Dim fi As File = New Data.File()
       Dim byteArray As Byte() = System.IO.File.ReadAllBytes(pathFile)
       Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)

       fi.Title = fileName
       Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(fi, stream, "*/*")
       request.ChunkSize = 1048576

       AddHandler request.ProgressChanged, New Action(Of IUploadProgress)(AddressOf Request_ProgressChanged)

       request.Upload()  

       Dim fileUpload As File = request.ResponseBody

       Return fileUpload
End Function

我阅读了文档,但是我找不到这种情况的例子。

更新

我更改了身份验证应用程序以使用之前保存的刷新令牌的常规Google帐户,但结果是相同的。
此问题与问题264有关,我的问题是:是否可以上传超过1小时?

2 个答案:

答案 0 :(得分:2)

除了云端硬盘OAuth范围之外,您还需要请求&#34;离线&#34; ACCESS_TYPE。当您提出此请求时,身份验证响应将包含刷新令牌,您可以使用该令牌在旧证书过期时获取新的访问令牌。

图书馆应该透明地处理大部分内容,你可能只需要通过&#34;离线&#34;您的身份验证请求中的范围。

更多信息:https://developers.google.com/accounts/docs/OAuth2WebServer#offline

答案 1 :(得分:0)

我无法识别您正在使用的库,但是如果它可以访问所有OAuth2铃声和口哨,您应该能够获得刷新令牌,并在此过期时,在到期时或之前获取新的访问令牌。