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

问题描述 投票:3回答:3

我正在使用ASP.NET Web API和.NET的Google.Apis.Drive.v2客户端库将文件上传到用户云端硬盘。

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

asp.net asp.net-web-api google-drive-api
3个回答
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%目录中。

您要做的是创建自己的IDataStore实现,并改用它。执行此操作的代码很广泛。我目前最接近的示例是一个将从database加载刷新令牌的示例。我还没有时间创建与此相关的教程,但是该项目位于GitHub上。 Google-Dotnet-Samples/Authentication欢迎您试用。我将检出一个数据库,您应该能够对其进行更改,以便向其提交刷新令牌。


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 ....
    }

0
投票

尽管问了问题已经两年了,但今天我遇到了同样的情况,我的解决方案是:

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);
© www.soinside.com 2019 - 2024. All rights reserved.