使用现有访问令牌创建Google Drive DriveService

时间:2014-10-28 22:49:25

标签: asp.net asp.net-web-api google-drive-api

我使用ASP.NET Web API和Google.Apis.Drive.v2 Client Library for .NET将文件上传到用户云端。

使用Drive Client Library for .NET的所有示例都需要身份验证流程。但是当我已经知道访问令牌时,我该如何创建DriveService?

3 个答案:

答案 0 :(得分:2)

通常,当您使用oauth2访问Google云端硬盘时,您会执行类似这样的操作

//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%将凭据信息存储在硬盘驱动器上。在{{1}}目录中。

您要做的是创建自己的IDataStore实现并使用它。执行此操作的代码非常广泛。我目前最接近的示例是将从database加载刷新令牌的示例。我没有时间创建一个教程来配合这个,但该项目正在选址GitHub。 Google-Dotnet-Samples/Authentication欢迎你来玩它。我会检查数据库,你应该能够改变它,让你提交一个refreshtoken。

答案 1 :(得分:1)

到目前为止,Svetoslav Georgiev的回答对我来说效果很好-非常感谢。 Google确实没有缺少.Net(Asp Core)样本等的帮助。总之,我确实遇到了一个问题,即引荐来源限制,因此,对答案的添加/轻微修改-一旦获得“服务” ”,并且要说要上传文件,您需要在隐蔽的HttpClient属性上设置引荐来源网址...

FilesResource.CreateMediaUpload uploadRequest;
byte[] byteArray = Encoding.UTF8.GetBytes(html);
using (var stream = new MemoryStream(byteArray))
    {
         uploadRequest = service.Files.Create(fileMetadata, stream, "text/html");
         uploadRequest.Service.HttpClient.DefaultRequestHeaders.Referrer = new Uri($"{baseUrl}");
         uploadRequest.Fields = "id";
         var progress = uploadRequest.Upload();
         if (progress.Exception != null)
         {
             throw progress.Exception;
         }
         var file = uploadRequest.ResponseBody;
         .... do what you will with file ....
    }

答案 2 :(得分:-1)

尽管问题问题已经过了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);