Google Drive Integration
In this blog we will see how to make Google Drive API integration with Xamarin Forms. Though there is no official Xamarin Forms libraries available in the Google resources for Drive Integration i have seen lots of queries in xamarin forums about google drive integration. So i thought of creating a POC in Xamarin Forms which integrates with Google drive with the existing .NET API for Drive.
NOTE : This is just a workaround for integrating GDrive, if you find any better solution please mention it in the comment.
Create a Xamarin.Forms Project:
Create a Xamarin.Forms project and add the below mentioned nuget packages:
- Xamarin.Auth – Platforms project
- Google.Apis.Drive.v2 – Both in Platforms & PCL.
- Xam.Plugin.Connectivity (Optional)
Note : Google.Apis.Drive.V2 is not the latest one but it has realtime update feature.
Before getting into code we need to register in google developer console to get google authentication key in order to access google drive. To get the web credentials please go through this link.
All queries raised in the Forums are related to GoogleWebAuthorizationBroker which is not available in this .NET profile. So I’ve tried to fix this with Xamarin.Auth which is a web based authentication using a Custom Authenticator
Now to Authenticate the user with google we will use Xamarin.Auth but in cross platform, so we need to create a Custom Renderer in each supported platform. Below added code snippet is for Android.
public class LoginPageRenderer : PageRenderer { string userJson; protected override void OnElementChanged(ElementChangedEventArgs<Page> e) { base.OnElementChanged(e); if (App.inAuthentication) return; App.inAuthentication = true; var auth = new RefreshOAuth2Authenticator( Constants.ClientId, Constants.ClientSecret, Constants.Scopes, new Uri(Constants.AuthorizationUri), new Uri(Constants.RedirectUri), new Uri(Constants.AccessTokenUri)); auth.AllowCancel = true; auth.Completed += async (sender, eventArgs) => { if (eventArgs.IsAuthenticated) { App.SuccessfulLoginAction.Invoke(); } var request = new OAuth2Request("GET", new Uri("https://www.googleapis.com/oauth2/v2/userinfo"), null, eventArgs.Account); var response = await request.GetResponseAsync(); if (response != null) { userJson = response.GetResponseText(); } StoringDataIntoCache(userJson, eventArgs.Account); }; auth.ShowErrors = false; var activity = Forms.Context as Activity; activity.StartActivity(auth.GetUI(activity)); } }
In the above code we have used a custom Authenticator which RefreshOAuth2Authenticator as the default OAuthenticator doesn’t gives us Refresh token.
With LoginRenderer we will authenticate the User and using the Authentication completed event we can get the response from the Redirecting URL and store it in the Account store present in Xamarin.Auth.
Now to initiate a Google DriveService we need a UserCredentials or ServiceAccountCredentials. Service account credentials works fine without any additional steps mentioned above. But for UserCredentials we need a ClientSecret, AccessToken, RefreshToken.
To Generate a TokenResponse of the UserCredential we will use DependencyService using which we can a generate a TokenResponse from the authenticated user credentials saved in the Xamarin.Auth account store.
The below attached image refers to the Shared TokenIssuer DependencyService for all platforms.
UserAccount – refers to the AccountStore created for the Authenticated user using Xamarin.Auth.
To know about google drive supported list of MIME types click here.
Now the pending actions are creating a UI flow for Authenticating the User and Getting the List of files available in the Drive which purely depends on requirements how one wants to do it.
Summary
In this blog i have shared my idea/ workaround about how to integrate google drive with xamarin forms. As mentioned early it all started as a POC, you find the fully functional sample along with the above discussed piece of codes in Github. Additional information Google sign in using web based authentication will be made invalid by google in future as per the google docs, until that this approach should work fine. If you have any suggestions or improvements to this please add it in the comments section.
Could you share your source code for this sample?
LikeLiked by 1 person
You can find the code here https://github.com/Dineshbala1/GoogleDriveAPI-XamarinForms
LikeLike
I am Receiving the error: disallowed_useragent
LikeLike
It’s exelent work! Thank’s.
LikeLike
would be great if you do a video on this from scratch.Thanks
LikeLike
It shows disallowed_useragent error
LikeLike
And can you please help me out for apply this in xamarin forms application(neither PCL nor shared).
LikeLike
This is an outdated article, but there should be an option in the latest auth library. I’m not sure it’s been a while since I worked on this.
LikeLike
Do you have any solution for Xamarin forms only means without Portable project???
LikeLike
Nice blog post. Perhaps you can update your Github example to the latest Xamarin.Forms. Most of the code in the renderers is obsolete…
LikeLike
Forgot to mention that the RealTime API is obsolete as well.
https://developers.google.com/realtime/overview
LikeLike
It was written long time ago: I’ve been working on similar bindings project soon will be writing a different article with the latest version, since google real-time API are absolete.
LikeLike
Been struggling with getting user credential, although I have gotten access and refresh tokens OK. I am looking forward to your upcoming article and its code. Any direction you might be able to give now on acquiring the user credential with current Xamarin Forms and Google Apis?
LikeLike
Why we need use CustomRender? How to use directly in PCL?
Thank!
LikeLike
How about CustomRenderer code for iOS and UWP?
LikeLike
When you have time, could you please re-create this sample in NET Standard plase! Thanks!
LikeLike