Google OAuth2:何时以及如何使用刷新令牌 [英] Google OAuth2: When and how to use refresh token
问题描述
我有一个已安装的c#应用程序,其代码可以正常工作,该应用程序获取授权码并将其交换为访问令牌.我存储了刷新令牌.我知道有时需要使用它来获取新的访问令牌.假设我定期调用以下方法来监视与我的云端硬盘帐户共享的文件.
I have an installed c# app with code working that gets the authorization code and exchanges it for an access token. I am storing off the refresh token. I know at some point I need to use it to get a new access token. Let's assume that I am periodically calling the following method to monitor the files that have been shared with my Drive account.
/// <summary>
/// Retrieve a list of File resources.
/// </summary>
/// <param name="service">Drive API service instance.</param>
/// <returns>List of File resources.</returns>
public static List<File> retrieveAllFiles(DriveService service) {
List<File> result = new List<File>();
FilesResource.ListRequest request = service.Files.List();
request.Q = "sharedWithMe and trashed=false";
do {
try {
FileList files = request.Fetch();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
request.PageToken = null;
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
}
我认为在某个时候对service.Files.List()的调用将失败.我怎么知道它由于访问令牌过期而失败,以及使用刷新令牌的代码是什么?我已经有一些代码(如下)是我从
I assume that at some point the call to service.Files.List() is going to fail. How do I know it has failed due to an expired access token and what is the code to use the refresh token? I already have some code (below) that I gleaned from here to use the refresh token. Will this method get called when the access token expires?
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// If we already have a RefreshToken, use that
if (!string.IsNullOrEmpty(RefreshToken))
{
state.RefreshToken = RefreshToken;
if (arg.RefreshToken(state)) {
mTextBox.Text = "RF: " + RefreshToken;
return state;
}
}
// authCode is a TextBox on the form
var result = arg.ProcessUserAuthorization(mTextBox.Text, state);
RefreshToken = state.RefreshToken;
return result;
}
推荐答案
如果仍然有人在刷新AccessToken时遇到问题,也许可以帮助您找到解决方案:
If someone still have Problems with refreshing the AccessToken, maybe this can help you finding a solution:
Google.GData.Client.RequestSettings settings = new RequestSettings("<AppName>");
Google.GData.Client.OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = "<YourClientId>",
ClientSecret = "<YourClientSecret>",
AccessToken = "<OldAccessToken>", //really necessary?
RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
RefreshToken = "<YourRefreshToken>",
AccessType = "offline",
TokenType = "refresh",
Scope = "https://www.google.com/m8/feeds/" //Change to needed scopes, I used this for ContactAPI
};
try
{
Google.GData.Client.OAuthUtil.RefreshAccessToken(parameters);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
这篇关于Google OAuth2:何时以及如何使用刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!