如何通过.NET中的Google Drive SDK使用刷新令牌生成访问令牌?

ruf*_*ufo 7 .net google-drive-api

我有一个使用Google Drive访问用户文件的.NET应用程序.我能够获得授权代码,并且我能够通过AccessToken和RefreshToken交换授权代码.问题是我无法刷新访问令牌,并在一小时后过期.

与此问题类似:如何通过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;        
        }
    }
Run Code Online (Sandbox Code Playgroud)

ruf*_*ufo 8

我研究了一个更合适的样本:GoogleApisSample的Tasks.WinForms.NoteMgr ......然后我找到了解决方案.

解决方案在下面的代码中.它的关键部分是调用arg.RefreshToken(state);

谢谢.

    public static Authentication.IAuthenticator UseSavedAuthorization()
    {          

        var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
        provider.ClientIdentifier = ClientID;
        provider.ClientSecret = ClientSecret;

        OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getState);

        auth.LoadAccessToken();

        return auth;             
    }


public static IAuthorizationState getState(NativeApplicationClient arg)
    {
        IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue(), 
                DriveService.Scopes.DriveFile.GetStringValue() , DriveService.Scopes.Drive.GetStringValue()
        });
        state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

        state.RefreshToken = "<refresh token previously saved>";        
        arg.RefreshToken(state); 

        return state; 
    }`
Run Code Online (Sandbox Code Playgroud)