Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate access token using refresh token through Google Drive SDK in .NET?

I have a .NET application that is using Google Drive to access the user's file. I am able to get the authorization code, and I have been able to exchange the authorization code by the AccessToken and the RefreshToken. The issue is that I cannot refresh the access token, and it expires after an hour.

Similar to this question: How to generate access token using refresh token through google drive API? except that I am working in .NET (using the Google.APIs... DLLs).

I am aware of this: https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh however, I am expecting some sort of method available in the IAuthorizationState or OAuth2Authenticator object to allow me refresh the access token.

Please advise. Thanks.

Please note that using this code I am able to get the Access Token. It is just that I am expecting this code to be inside the 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;        
        }
    }
like image 737
rufo Avatar asked Jul 12 '12 18:07

rufo


People also ask

How can I get access token and refresh token?

To get an access token using a refresh token, you must first get the refresh token. Then you use the refresh token from then on to generate an access token.

Can refresh token be used as access token?

Refresh Token are typically longer lived than Access Tokens and used to request a new Access Token without forcing user authentication. Unlike Access Tokens, Refresh Tokens are only used with the Authorization Server and are never sent to a web service.


1 Answers

I studied a more suitable sample: the Tasks.WinForms.NoteMgr of the GoogleApisSample... and with it I found the solution.

The solution is in the code below. The key part of it is calling arg.RefreshToken(state);

Thanks.

    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; 
    }`
like image 152
rufo Avatar answered Oct 17 '22 04:10

rufo