Quartz.NET中的Google Drive无需每次都重新进行身份验证

时间:2015-12-21 11:53:42

标签: c# asp.net oauth google-drive-api

  • .NET 4.51使用Google.Apis。* NuGet包

我正在尝试实现所谓的“离线访问” https://developers.google.com/identity/protocols/OAuth2WebServer

在这种情况下,您拥有ClientId,ClientSecret RefreshToken。此外,您不希望任何用户交互来授权访问。

我在Quartz.NET找到了一个连接到Google云端硬盘并下载特定文件的工作。这一切都有效,但每次我被要求授权该应用程序。这是提供RefreshToken的地方可以减轻这种情况。

但是对于我的生活,我无法弄清楚如何将刷新令牌传递给AuthorizeAsync()。

我的代码如下:

private bool InternalLogin(string aClientId, string aClientSecret, string aUserName, out DriveService aGoogleDrive)
{
    //Scopes for use with the Google Drive API
    string[] scopes = Scopes.ToArray();
    aGoogleDrive = null;

    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 = aClientId,
            ClientSecret = aClientSecret
        },
            scopes,
            aUserName,
            CancellationToken.None,
            //This cannot be the FileStore it has to be something else. But what?
            new FileDataStore("MyApp.GoogleDrive.Auth.Store")
            ).Result;

        aGoogleDrive = new DriveService(new BaseClientService.Initializer
        {
            ApplicationName = "MyApp Google Drive Helper",
            HttpClientInitializer = credential
        });
    }
    catch (Exception)
    {
        return false;
    }

    return true;
}

那么有人可以告诉我如何/在哪里提供RefreshToken,这样当我部署我的ASP.NET WebForms应用程序时,它“只能工作”,而不需要每次都使用Google进行授权吗?

1 个答案:

答案 0 :(得分:0)

您应该将RefreshToken提供给您正在创建的credentials对象。这将导致RefreshToken自动用于生成新的AccessToken:

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
            {
                ClientId = ClientId,
                ClientSecret = ClientSecret
            },
            Scopes = new[] { DriveService.Scope.Drive }
    });

var credential = new UserCredential(_flow, request.UserIdentifier, new TokenResponse
    {
        AccessToken = AccessToken,
        RefreshToken = RefreshToken
    });
var service = new DriveService(new BaseClientService.Initializer
    {
        ApplicationName = "MyApp",
        HttpClientInitializer = credential,
        DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.Exception | ExponentialBackOffPolicy.UnsuccessfulResponse503
    });