我正在使用ASP.NET Web API和Google.Apis.Drive.v2 Client Library for .NET將文件上傳到用戶Drive。使用現有訪問令牌創建Google Drive DriveService
使用適用於.NET的Drive Client Library的所有示例都需要身份驗證流程。但是當我已經知道訪問令牌時,我應該如何創建DriveService?
我正在使用ASP.NET Web API和Google.Apis.Drive.v2 Client Library for .NET將文件上傳到用戶Drive。使用現有訪問令牌創建Google Drive DriveService
使用適用於.NET的Drive Client Library的所有示例都需要身份驗證流程。但是當我已經知道訪問令牌時,我應該如何創建DriveService?
通常,當您訪問使用谷歌驅動器的oauth2你會做這樣的事情
//Scopes for use with the Google Drive API
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
// 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 = CLIENT_ID
, ClientSecret = CLIENT_SECRET }
,scopes
,Environment.UserName
,CancellationToken.None
,new FileDataStore("Daimto.GoogleDrive.Auth.Store")
).Result;
這將創建一個UserCredential
然後你可以用它來創建一個DriveService
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
你要去的問題FileDataStore
將證書信息存儲在硬盤上。在%AppData%
目錄中。
你想要做的是創建你自己的IDataStore的實現,並使用它。執行此操作的代碼非常廣泛。我目前最接近的例子是將從database加載刷新令牌的例子。我沒有時間去創建一個教程,但該項目正在GitHub上。 Google-Dotnet-Samples/Authentication歡迎您隨身攜帶。我會檢查數據庫,你應該能夠改變它,讓你向它提交一個refreshtoken。
儘管有過2次年以來的問題已經被問的事實,今天我遇到了同樣的情況,我的解決辦法是:
var valid_token = "Pass_the_valid_token_here";
var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse()
{
AccessToken = valid_token,
ExpiresInSeconds = 3600,
Issued = DateTime.Now
};
var fakeflow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "fakeClientId",
ClientSecret = "fakeClientSecret"
}
});
UserCredential credential = new UserCredential(fakeflow, "fakeUserId", token);
var serviceInitializer = new BaseClientService.Initializer()
{
//ApplicationName = "Storage Sample",
HttpClientInitializer = credential
};
DriveService service = new DriveService(serviceInitializer);
驅動器服務需要您發送UserCredential。您可能必須創建自己的idatastore實現來發送刷新令牌。 – DaImTo 2014-10-29 10:23:22
我該怎麼做? – 2014-10-29 14:21:40