如何使用刷新令牌为 Google SpreadsheetsService 获取新的访问令牌

How do I use a refresh token to get a new access token for Google SpreadsheetsService

我正在尝试构建一个读取和写入私有 Google 电子表格的应用程序。为此,我需要使用 Google OAuth2.0 .

我的问题是我在 1 小时后无法访问。我认为这意味着没有正确使用刷新令牌。这是我处理身份验证的代码:

public static SpreadsheetsService AuthenticateOauth(string clientId, string clientSecret, string userName)
    {

        string[] scopes = new string[] { DriveService.Scope.Drive,  // view and manage your files and documents
                                         DriveService.Scope.DriveAppdata,  
                                         DriveService.Scope.DriveAppsReadonly,   
                                         DriveService.Scope.DriveFile,   
                                         DriveService.Scope.DriveMetadataReadonly,   
                                         DriveService.Scope.DriveReadonly,   
                                         "https://spreadsheets.google.com/feeds",
                                         "https://docs.google.com/feeds"

        };  


        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 = clientId, ClientSecret = clientSecret }
                                                                                         , scopes
                                                                                         , userName
                                                                                         , CancellationToken.None
                                                                                         , new FileDataStore("MY.APP.Auth.Store")).Result;

            SpreadsheetsService service = new SpreadsheetsService(My App");
            var requestFactory = new GDataRequestFactory("My App");

            requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
            service.RequestFactory = requestFactory;

            return service;
        }
        catch (Exception ex)
        {


            Console.WriteLine(DateTime.Now.ToString("HH:mm") + ": An authentication error occurred: " + ex.InnerException);
            return null;

        }

    }

如何正确使用刷新令牌?

您正在使用当前的 Google .NET 客户端库进行身份验证。 当您创建服务时,它通常会在需要时自动刷新您的访问令牌。但是,您正在将访问令牌发送到旧的 Gdata 库,该库不会自动刷新它。

如果您创建了一个驱动器服务并且运行一个针对它的虚拟请求每小时一次,它会在需要时为您刷新您的访问令牌。

var service = new DriveService(new BaseClientService.Initializer() {HttpClientInitializer = credential,
                                                                            ApplicationName = "Drive API Sample",});

// Dummy request example:
FilesResource.ListRequest list = service.Files.List();
list.MaxResults = 1;
list.Q = "title=dummysearch";
FileList dummyFeed = list.Execute();
// End of Dummy request