Google Drive API with Xamarin Forms

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:

  1. Xamarin.Auth – Platforms project
  2. Google.Apis.Drive.v2 – Both in Platforms & PCL.
  3. 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.

googledriveconstants
Google Drive Credentials

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.

accountstore

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.

DriveService
Creating a Drive Service

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.

tokenissuer

UserAccount – refers to the AccountStore created for the Authenticated user using Xamarin.Auth.

FileList
Get File List from Google Drive

To know about google drive supported list of MIME types click here.

Nexus 5 (Lollipop) Screenshot 822
Google Drive Integrated – File List

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.

Advertisements

11 thoughts on “Google Drive API with Xamarin Forms

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s