Iβm trying to create a desktop application that can display files and folders in a Google Drive account. At this point I can do it, but there is one problem. I need to re-register every time I want to open a Google Drive account from my application. Is it possible to use stored local AccessToken / Refresh tokens to avoid re-authorization every time?
This uses the method that is used to obtain authorization.
private IAuthorizationState GetAuthorization(NativeApplicationClient arg) { IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" }); // Get the auth URL: state.Callback = new Uri("urn:ietf:wg:oauth:2.0:oob"); UriBuilder builder = new UriBuilder(arg.RequestUserAuthorization(state)); NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query); queryParameters.Set("access_type", "offline"); queryParameters.Set("approval_prompt", "force"); queryParameters.Set("user_id", email); builder.Query = queryParameters.ToString(); //Dialog window wich returns authcode GoogleWebBrowserAuthenticator a = new GooogleWebBrowserAuthenticator(builder.Uri.ToString()); a.ShowDialog(); //Request authorization from the user (by opening a browser window): string authCode = a.authCode; // Retrieve the access token by using the authorization code: return arg.ProcessUserAuthorization(authCode, state); }
SOLVE:
To call methods from Google Drive sdk, you first need to specify an instance of the service:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, GoogleDriveHelper.CLIENT_ID, GoogleDriveHelper.CLIENT_SECRET); var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); Service = new DriveService(auth);
These CLIENT_ID and CLIENT_SECRET you will receive after registering in the application on the Google API console.
Then you need to define a GetAuthorization procedure, which might look like this:
private IAuthorizationState GetAuthorization(NativeApplicationClient arg) { IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" }); state.Callback = new Uri("urn:ietf:wg:oauth:2.0:oob"); state.RefreshToken = AccountInfo.RefreshToken; state.AccessToken = AccountInfo.AccessToken; arg.RefreshToken(state); return state; }
It will work if you already have update and access tokens (at least Refresh). Therefore, first you need to authorize the user account.
You can then use this instance of the service to call sdk methods. Hope this helps someone.