Search This Blog

Sunday 29 September 2019

Login with google in Xamarin(Android/iOS)




Install Xamarin.Auth library in your project.

Right-click on your Project Solution and select Manage Nuget for the solution.
Search for the Xamarin.Auth library and install it in all the project (Android, iOS, Xamarin Project).



Note: Another required libraries are Newtonsoft.Json and System.Net.Http

Initialize the Xamarin.Auth library in Android & iOS Project

Xamarin.Android  Project
Initialize the Xamarin.Auth library in MainActivity.cs class.

MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;
    base.OnCreate(savedInstanceState);
 
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, savedInstanceState); // for login with google
 
    // User-Agent tweaks for Embedded WebViews
    global::Xamarin.Auth.WebViewConfiguration.Android.UserAgent = "Mozilla/5.0 (Linux; Android 4.4.4; One Build/KTU84L.H4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.135 Mobile Safari/537.36";
 
    #region Other Xamarin.Auth intialization properties
 
    // Xamarin.Auth CustomTabs Initialization/Customisation
 
    //global::Xamarin.Auth.CustomTabsConfiguration.ActionLabel = null;
    //global::Xamarin.Auth.CustomTabsConfiguration.MenuItemTitle = null;
    //global::Xamarin.Auth.CustomTabsConfiguration.AreAnimationsUsed = true;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsShowTitleUsed = false;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsUrlBarHidingUsed = false;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsCloseButtonIconUsed = false;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsActionButtonUsed = false;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsActionBarToolbarIconUsed = false;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsDefaultShareMenuItemUsed = false;
    //global::Xamarin.Auth.CustomTabsConfiguration.ToolbarColor = Android.Graphics.Color.LightBlue;
 
    //// ActivityFlags for tweaking closing of CustomTabs
    //// please report findings!
    //global::Xamarin.Auth.CustomTabsConfiguration.
    //   ActivityFlags =
    //        global::Android.Content.ActivityFlags.NoHistory
    //        |
    //        global::Android.Content.ActivityFlags.SingleTop
    //        |
    //        global::Android.Content.ActivityFlags.NewTask;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsWarmUpUsed = true;
    //global::Xamarin.Auth.CustomTabsConfiguration.IsPrefetchUsed = true;
    #endregion
 
       LoadApplication(new App());
}

Xamarin.iOS Project
Initialize the Xamarin.Auth library in AppDelegate.cs class.

AppDelegate.cs
using System;
using System.Collections.Generic;
using System.Linq;
 
using Foundation;
using UIKit;
 
namespace Mechat.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());
            global::Xamarin.Auth.Presenters.XamarinIOS.AuthenticationConfiguration.Init();
            return base.FinishedLaunching(app, options);
        }
    }
}
 

Xamarin.Form Project
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"          
             mc:Ignorable="d"
             x:Class="Mechat.MainPage">
    <StackLayout Margin="10">
        <Button Text="Click here to login with google" Clicked="Button_Clicked"/>
    </StackLayout>
 
</ContentPage>
 
MainPage.cs
using Mechat.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Auth;
using Xamarin.Forms;
 
namespace Mechat
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void Button_Clicked(object sender, EventArgs e)
        {
            var authenticator = new OAuth2Authenticator
                         (
                           "Google client ID",
                           "email profile",
                            new System.Uri( "https://accounts.google.com/o/oauth2/auth"),
                            new System.Uri("https://www.google.com")
                          );
 
            authenticator.AllowCancel = true;
 
            var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
            presenter.Login(authenticator);
 
            authenticator.Completed += async (senders, obj) =>
            {
                if (obj.IsAuthenticated)
                {
                    var clientData = new HttpClient();
 
                    //call google api to fetch logged in user profile info 
                    var resData = await clientData.GetAsync("https://www.googleapis.com/oauth2/v3/userinfo?access_token=" + obj.Account.Properties["access_token"]);
                    var jsonData = await resData.Content.ReadAsStringAsync();
 
                    // deserlize the jsondata and intilize in GoogleAuthClass
                    GoogleAuthClass googleObject = JsonConvert.DeserializeObject<GoogleAuthClass>(jsonData);
 
                    //you can access following property after login
                    string email = googleObject.email;
                    string photo = googleObject.picture;
                    string name = googleObject.name;
                }
                else
                {
                    //Authentication fail
                    // write the code to handle when auth failed
                }
            };
            authenticator.Error += onAuthError;
        }
 
        private void onAuthError(object sender, AuthenticatorErrorEventArgs e)
        {
            DisplayAlert("Google Authentication Error", e.Message, "OK");
        }
    }
 
}

Note: You will get google client id from the google developer console. there you need to create a project.

GoogleAuthClass.cs
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Mechat.Model
{
   public class GoogleAuthClass
    {
        public string email { get; set; }
        public bool email_verified { get; set; }
        public string name { get; set; }
        public string picture { get; set; }
    }
 
}


3 comments:

  1. getting null exception and this gets called
    authenticator.Error += onAuthError;

    ReplyDelete
  2. Oh, Might be something missing in authentication can you please check this video might be it help you : https://youtu.be/16lzncZt61A

    ReplyDelete
  3. Thank you for your blog but this code is not working in net8.0-android. If possible, please update the code.

    ReplyDelete

Popular Posts