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

时间:2015-09-23 10:56:05

标签: c# oauth-2.0 google-oauth

我正在尝试构建一个读取和写入私人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;

        }

    }

如何正确使用刷新令牌?

1 个答案:

答案 0 :(得分:1)

您正在使用当前的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