我有一個使用Google Drive訪問用戶文件的.NET應用程序。我能夠獲得授權碼,並且能夠通過AccessToken和RefreshToken交換授權碼。問題是我無法刷新訪問令牌,並在一小時後過期。如何通過.NET中的Google Drive SDK使用刷新令牌生成訪問令牌?
與此問題類似:How to generate access token using refresh token through google drive API?除了我在.NET中工作(使用Google.APIs DLLs)。
我意識到這一點:https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh然而,我期待在IAuthorizationState或OAuth2Authenticator對象中提供某種方法來允許我刷新訪問令牌。
請指教。謝謝。
請注意,使用此代碼我可以獲得訪問令牌。這只是我期待這段代碼在Google API裏面。
public class OAuth2AccessTokenReponse
{
public string access_token;
public int expires_in;
public string token_type;
}
public static string refreshAccessToken()
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
byte[] response = client.UploadValues("https://accounts.google.com/o/oauth2/token", new System.Collections.Specialized.NameValueCollection(){
{"client_id", ClientID},
{"client_secret", ClientSecret},
{"refresh_token", "XXXXX"},
{"grant_type", "refresh_token"}
});
string sresponse = System.Text.Encoding.Default.GetString(response);
OAuth2AccessTokenReponse o = (OAuth2AccessTokenReponse) Newtonsoft.Json.JsonConvert.DeserializeObject(sresponse, typeof(OAuth2AccessTokenReponse));
return o.access_token;
}
}
我正在使用庫。我的項目是一個「已安裝的應用程序」。在我的測試中,它沒有奏效。我能夠首先訪問應用程序(在此期間打開/關閉我的應用程序)。由於這個問題,應用程序在一小時之後被拒絕訪問。你有這樣的工作樣本嗎?我正在使用Task.SimpleOAuth2示例(當然擴展它)。 – rufo 2012-07-12 19:33:59
用戶第一次授予訪問您的應用的權限時,您只會獲得刷新令牌,因此您必須將其存儲以供將來使用。我猜是第二次嘗試應用程序時,您只檢索了一個訪問令牌(並且沒有存儲刷新令牌),因此在到期後無法請求新的訪問令牌。谷歌驅動器有一個完整的示例,但它不是一個安裝的應用程序:https://developers.google.com/drive/examples/dotnet – 2012-07-12 19:48:24
克勞迪奧,是的 - 我第一次得到刷新令牌並保存它。下一次我嘗試使用它(通過設置state.RefreshToken = {my refresh token},並使用authorization.LoadAccessToken()。這不起作用。注意:我還查看了DrEdit.Net示例,它似乎對我來說,他們正在做我在做什麼,請注意,我的解決方法代碼來自上面的工作(所以我確實有正確的刷新)謝謝你的幫助 – rufo 2012-07-12 20:22:37