{"id":32873,"date":"2017-08-18T11:46:03","date_gmt":"2017-08-18T18:46:03","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=32873"},"modified":"2019-03-25T19:21:43","modified_gmt":"2019-03-26T03:21:43","slug":"native-android-facebook-authentication-azure-app-service","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/native-android-facebook-authentication-azure-app-service\/","title":{"rendered":"Native Android Facebook Authentication with Azure App Service"},"content":{"rendered":"<p>\t\t\t\tAuthentication<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/icon_114x114.png\" alt=\"\" width=\"114\" height=\"114\" class=\"alignright size-full wp-image-32874\" \/> is critical to applications success. Look at your app, and I bet the very first things that your users will do is sign up or log in to their account. This will probably, in turn, leverage some form of social authentication. Each social authentication provider is a little bit different, and some, such as Facebook, offer a native SDK to simplify the login process and offer additional functionality specific to their service. Previously, we looked at how to integrate the <a href=\"https:\/\/blog.xamarin.com\/native-facebook-authentication-with-azure-app-service\/\">Facebook SDK for iOS to offer a native login experience<\/a> and how to integrate with Azure Mobile Apps, part of Azure App Service. Today, I&#8217;ll show you how to log in with the Android Facebook SDK to simplify the login process on Android and with Xamarin.Forms.<\/p>\n<h2>Why use Native SDKs?<\/h2>\n<p><a href=\"https:\/\/azure.microsoft.com\/en-us\/services\/app-service\/mobile\/\" target=\"_blank\">Azure Mobile Apps<\/a> offers a simple <code>LoginAsync<\/code> method that will invoke a secure login process leveraging Chrome Custom Tabs. However, this still requires users to type in their existing user name and password, even if they already have the provider&#8217;s application installed on their device. Leveraging the native SDK for Facebook, Google, or Microsoft enables a secure and streamlined experience and provides native user interface controls that make your users feel safe when logging in. <\/p>\n<h2>Signing up for Facebook Auth<\/h2>\n<p>Before we even begin to integrate Facebook authentication into our app, we must register a new application on the <a href=\"https:\/\/developers.facebook.com\/\">Facebook Developer site<\/a>. <\/p>\n<p>Next, we&#8217;ll want to add a proper oAuth redirect, which can be done by adding a &#8220;Facebook Login&#8221; product:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AddProduct.png\" alt=\"\" width=\"1258\" height=\"422\" class=\"aligncenter size-full wp-image-32875\" \/><\/p>\n<p>For this application, we&#8217;ll be using Azure App Service, which means we can specify a redirect URL such as:<\/p>\n<pre><code>https:\/\/[AppServiceApplicationURL]\/.auth\/login\/facebook\/callback<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AddRedirect.png\" alt=\"\" width=\"1543\" height=\"516\" class=\"aligncenter size-full wp-image-32876\" \/><\/p>\n<p>You can learn more about configuring this by reading through the <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/app-service-mobile\/app-service-mobile-how-to-configure-facebook-authentication\">Azure App Service Authentication with Facebook documentation<\/a>. <\/p>\n<h2>Getting Started<\/h2>\n<p>With our Facebook application set up, we can now start integrating the Facebook Android SDK, which is available from <a href=\"https:\/\/www.nuget.org\/packages\/Xamarin.Facebook.Android\/\">NuGet<\/a>, into our application. This is the Xamarin.Android binding to the <a href=\"https:\/\/developers.facebook.com\/docs\/android\/\">official SDK<\/a> provided by Facebook, which allows us to use all of the features available to Java and Kotlin developers.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/FacebookNuGet.png\" alt=\"\" width=\"1289\" height=\"281\" class=\"aligncenter size-full wp-image-32877\" \/><\/p>\n<p>When installing this NuGet, it&#8217;s important for us to ensure that we have <a href=\"https:\/\/blog.xamarin.com\/mastering-android-support-libraries\/\">installed the latest Android Support Libraries<\/a> as well, as they are a dependency.<\/p>\n<h2>Configuring Our App<\/h2>\n<p>There&#8217;s a bit of additional setup that we must perform before implementing the login process. We can add the Facebook App Id that we received and our app&#8217;s name inside of our string resources:<\/p>\n<pre><code>Coffee Cups\r\n605355546285789<\/code><\/pre>\n<p>The Facebook SDK will look for this metadata that we can expose using assembly flags. I tend to add these into my AssemblyInfo.cs file along with permissions that are required:<\/p>\n<pre><code>[assembly: MetaData(\"com.facebook.sdk.ApplicationId\", Value = \"@string\/app_id\")]\r\n[assembly: MetaData(\"com.facebook.sdk.ApplicationName\", Value = \"@string\/app_name\")]\r\n\r\n[assembly: Permission(Name = Android.Manifest.Permission.Internet)]\r\n[assembly: Permission(Name = Android.Manifest.Permission.WriteExternalStorage)]<\/code><\/pre>\n<h2>Registering Our Android App with Facebook<\/h2>\n<p>We can add a new platform of Android in the Facebook Developer site under <em>Settings<\/em>, so Facebook has additional information about our application. This will require our package name, class name, and key hashes.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AddAndroidPlatform.png\" alt=\"\" width=\"943\" height=\"383\" class=\"aligncenter size-full wp-image-32878\" \/><\/p>\n<p>Our package name comes directly from the AndroidManifest.xml. The class name can be set manually on the Main Activity such as:<\/p>\n<pre><code>[Activity (Label = \"Coffee Cups\", Icon = \"@drawable\/icon\",\r\n        Name = \"com.refractored.coffeecups.MainActivity\",\r\n        MainLauncher = true,\r\n        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]<\/code><\/pre>\n<p>Finally they key hashes can be found using the <a href=\"https:\/\/blog.xamarin.com\/simplified-android-keystore-signature-disovery\/\">Android Keystore Signature tool for Visual Studio<\/a>. For now, we can just use the default debug keystore, however, we would want to use the keystore that we use to sign our application with before publishing the app to the app store.<\/p>\n<h2>Adding a Facebook Login Button<\/h2>\n<p>Now, it&#8217;s time for us to finally add in a login button to kick off the entire process. If you&#8217;re developing a Xamarin.Android application using a native Android user interface, you can simply insert the LoginButton that comes from the Facebook SDK:<\/p>\n<pre><code>\r\n\r\n        \r\n<\/code><\/pre>\n<h2>Xamarin.Forms Custom Control<\/h2>\n<p>If you&#8217;re using Xamarin.Forms, we must write a very small custom control. First, in our shared code, create a FacebookLoginButton that we can access in our XAML:<\/p>\n<pre><code>public class FacebookLoginButton : Xamarin.Forms.View\r\n{\r\n}<\/pre>\n<p><\/code><\/p>\n<p>This can then be added into any page of our application:<\/p>\n<pre><\/code>\r\n\r\n    \r\n        \r\n            <Label \/>\r\n            \r\n        \r\n    \r\n<\/code><\/pre>\n<p>Then we can write a small custom renderer that will display the native login button:<\/p>\n<pre><code>using CoffeeCups.View;\r\nusing Xamarin.Forms;\r\nusing CoffeeCups.Droid;\r\nusing Xamarin.Forms.Platform.Android;\r\nusing Xamarin.Facebook.Login.Widget;\r\n\r\n[assembly: ExportRenderer(typeof(FacebookLoginButton), typeof(FacebookLoginButtonRenderer))]\r\nnamespace CoffeeCups.Droid\r\n{\r\n    public class FacebookLoginButtonRenderer : ViewRenderer\r\n    {\r\n        LoginButton facebookLoginButton;\r\n        protected override void OnElementChanged(ElementChangedEventArgs e)\r\n        {\r\n            base.OnElementChanged(e);\r\n            if(Control == null || facebookLoginButton == null)\r\n            {\r\n                facebookLoginButton = new LoginButton(Forms.Context);\r\n                SetNativeControl(facebookLoginButton);\r\n            }\r\n        }\r\n        \r\n    }\r\n}<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screenshot_2017-08-17-10-46-51.png\" alt=\"\" width=\"360\" height=\"640\" class=\"aligncenter size-full wp-image-32879\" \/><\/p>\n<p>Since we're using the native Facebook SDK, when the users log in they will see the native Facebook login pop up, or, if they have the Facebook app installed, they can immediately log in with one button click:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screenshot_2017-08-17-10-46-59.png\" alt=\"\" width=\"720\" height=\"640\" class=\"aligncenter size-full wp-image-32880\" \/><\/p>\n<h2>Handling the Login Process<\/h2>\n<p>When the user logs in, we must handle the actual login events if it was successful, canceled, or if an error occurred. In our MainActivity, or whatever Activity the login button is shown on, we can implement a simple interface, IFacebookCallback, to handle these events. <\/p>\n<pre><code>class FacebookCallback : Java.Lang.Object, IFacebookCallback where TResult : Java.Lang.Object\r\n{\r\n    public Action HandleCancel { get; set; }\r\n    public Action HandleError { get; set; }\r\n    public Action HandleSuccess { get; set; }\r\n\r\n    public void OnCancel()\r\n    {\r\n        HandleCancel?.Invoke();\r\n    }\r\n\r\n    public void OnError(FacebookException error)\r\n    {\r\n        HandleError?.Invoke(error);\r\n    }\r\n\r\n    public void OnSuccess(Java.Lang.Object result)\r\n    {\r\n        HandleSuccess?.Invoke(result.JavaCast());\r\n    }\r\n}<\/code><\/pre>\n<p>Now, we can initialize the Facebook SDK, register for login callbacks, and handle them properly:<\/p>\n<pre><code>ICallbackManager callbackManager;\r\n\r\nprotected override void OnCreate (Bundle bundle)\r\n{\r\n\r\n   \/\/Standard OnCreate Intialization\r\n\r\n    FacebookSdk.SdkInitialize(ApplicationContext);\r\n    callbackManager = CallbackManagerFactory.Create();\r\n\r\n    var loginCallback = new FacebookCallback\r\n    {\r\n        HandleSuccess = loginResult =&gt; \r\n        {\r\n\r\n            var facebookToken = AccessToken.CurrentAccessToken.Token;\r\n            \/\/Login here\r\n        },\r\n        HandleCancel = () =&gt; \r\n        {\r\n            \/\/Handle Cancel  \r\n        },\r\n        HandleError = loginError =&gt; \r\n        {\r\n            \/\/Handle Error        \r\n        }\r\n    };\r\n\r\n    LoginManager.Instance.RegisterCallback(callbackManager, loginCallback);\r\n\r\n    \/\/Finish or load Xamarin.Forms app here\r\n}\r\n\r\nprotected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\r\n{\r\n    base.OnActivityResult(requestCode, resultCode, data);\r\n\r\n    callbackManager.OnActivityResult(requestCode, (int)resultCode, data);\r\n}<\/code><\/pre>\n<p>Notice that we're now able to get access to the Facebook access token, which will enable us to log in and make additional calls to the Facebook service.<\/p>\n<h2>Logging in to App Service<\/h2>\n<p>With this token, we can log in to our Azure App Service using the <code>MobileServiceClient<\/code>. <\/p>\n<pre><code>var facebookToken = AccessToken.CurrentAccessToken.Token;\r\nvar token = new JObject();\r\ntoken[\"access_token\"] = facebookToken;\r\nvar user  = await Client.LoginAsync(MobileServiceAuthenticationProvider.Facebook, token);<\/code><\/pre>\n<p>When we do this, we\u2019ll get back a <code>MobileServiceUser<\/code> which contains a new token that's unique to our App Service's backend. It\u2019s worth noting that this token is not the same as the Facebook token we sent, and it should be stored to re-hydrate the <code>MobileServiceUser<\/code> in the future.<\/p>\n<h2>Learn More<\/h2>\n<p>As we have seen here, it's to our advantage to use the native authentication SDKs when possible in our application to streamline the login process for our users, which can be done with just a few lines of code. To learn more about <a href=\"https:\/\/azure.microsoft.com\/en-us\/services\/app-service\/mobile\/\">Azure Mobile Apps<\/a> as a backend for your mobile app, be sure to read through the <a href=\"https:\/\/azure.microsoft.com\/en-us\/documentation\/learning-paths\/appservice-mobileapps\/\">great documentation<\/a> including how to add <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/app-service-mobile\/app-service-mobile-xamarin-forms-get-started-users\">other login providers to your mobile applications<\/a> with custom URL schemes. Additionally, you can find my sample app <em>Coffee Cup<\/em>, which I used to demonstrated the concepts in this blog post, on <a href=\"https:\/\/github.com\/jamesmontemagno\/app-coffeecups\/tree\/facebook-auth\">GitHub<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Authenticationis critical to applications success. Look at your app, and I bet the very first things that your users will do is sign up or log in to their account. This will probably, in turn, leverage some form of social authentication. Each social authentication provider is a little bit different, and some, such as Facebook, offer a native SDK to simplify the login process and offer additional functionality specific to their service. Previously, we looked at how to integrate the <a href=\"https:\/\/blog.xamarin.com\/native-facebook-authentication-with-azure-app-service\/\">Facebook SDK for iOS to offer a native login experience<\/a> and how to integrate with Azure Mobile Apps, part of Azure App Service. Today, I&#8217;ll show you how to log in with the Android Facebook SDK to simplify the login process on Android and with Xamarin.Forms.<\/p>\n","protected":false},"author":544,"featured_media":41022,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[313,2,556],"tags":[5,1278,1276,1277,4,16],"class_list":["post-32873","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android","category-developers","category-integrations","tag-android","tag-authentication","tag-facebook","tag-login","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>Authenticationis critical to applications success. Look at your app, and I bet the very first things that your users will do is sign up or log in to their account. This will probably, in turn, leverage some form of social authentication. Each social authentication provider is a little bit different, and some, such as Facebook, offer a native SDK to simplify the login process and offer additional functionality specific to their service. Previously, we looked at how to integrate the <a href=\"https:\/\/blog.xamarin.com\/native-facebook-authentication-with-azure-app-service\/\">Facebook SDK for iOS to offer a native login experience<\/a> and how to integrate with Azure Mobile Apps, part of Azure App Service. Today, I&#8217;ll show you how to log in with the Android Facebook SDK to simplify the login process on Android and with Xamarin.Forms.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/32873","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/544"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=32873"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/32873\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/41022"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=32873"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=32873"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=32873"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}