{"id":20218,"date":"2015-08-05T10:31:03","date_gmt":"2015-08-05T14:31:03","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=20218"},"modified":"2015-08-05T10:31:03","modified_gmt":"2015-08-05T14:31:03","slug":"put-adal-xamarin-forms","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/put-adal-xamarin-forms\/","title":{"rendered":"Put Some Azure Active Directory in Xamarin.Forms"},"content":{"rendered":"<p>\t\t\t\tThe Azure Active Directory Authentication Library (aka ADAL) makes authentication with Azure Active Directory a breeze. We&#8217;ve already covered usage of ADAL in various posts on <a href=\"https:\/\/blog.xamarin.com\/authenticate-xamarin-mobile-apps-using-azure-active-directory\/\">authenticating with Active Directory<\/a>, <a href=\"https:\/\/blog.xamarin.com\/add-storage-to-your-apps-with-office-365\/\">adding storage<\/a>, and <a href=\"https:\/\/blog.xamarin.com\/add-collaboration-to-your-mobile-apps-with-sharepoint\/\">adding collaboration<\/a> (SharePoint) to your mobile apps. <img decoding=\"async\" class=\"alignright size-medium wp-image-20271\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/azure-active-directory-300x300.png\" alt=\"azure-active-directory\" width=\"150\" height=\"150\" \/>ADAL is available for various platforms and supports Xamarin.Android, Xamarin.iOS, and Windows Phone. It&#8217;s easy to integrate ADAL into these projects by adding a NuGet package. Although ADAL hasn&#8217;t released a specific Package for Xamarin.Forms, there have been many questions in the <a href=\"https:\/\/forums.xamarin.com\/26850\/xamairn-forms-and-azure-active-directory-authentication\">Xamarin forums<\/a> and on <a href=\"http:\/\/stackoverflow.com\/questions\/29293470\/azure-active-directory-authentication-with-pcl-xamarin-forms\">StackOverflow<\/a> about how to use ADAL in a Xamarin.Forms app.<\/p>\n<p>Recently, Vittorio Bertocci, Principal Program Manager at Microsoft, posted a <a href=\"http:\/\/www.cloudidentity.com\/blog\/2015\/07\/22\/using-adal-3-x-with-xamarin-forms\/\" target=\"_blank\">blog<\/a> about integrating ADAL into Xamarin.Forms apps using a PageRenderer. In this post, I&#8217;ll be sharing another way to integrate ADAL into Xamarin.Forms apps using Dependency Service, which is available in Xamarin.Forms.<\/p>\n<p>&nbsp;<\/p>\n<h2>Step 1: Create a Xamarin.Forms App<\/h2>\n<p>Create a Xamarin.Forms app in Xamarin Studio or Visual Studio. If you create this project with Visual Studio, it will create four projects: PCL, Android, iOS, and Windows Phone. In this solution, the Windows Phone project created with Xamarin.Forms uses the Silverlight framework, which has different requirements for implementing ADAL than iOS, Android, or Windows Runtime apps. So let&#8217;s add a Windows Phone 8.1 project, for which we&#8217;ll use the new Windows Runtime framework by following the steps in <a href=\"http:\/\/developer.xamarin.com\/guides\/cross-platform\/xamarin-forms\/windows\/\">the documentation<\/a>. Follow the guide and make sure your project structure looks similar to my solution below:<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-20219 size-full\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screen-Shot-2015-07-30-at-11.59.50-am.png\" alt=\"ADAL-In-Xamarin-Forms-01\" width=\"860\" height=\"472\" \/><\/p>\n<h2>Step 2: Add NuGet Package References<\/h2>\n<p>For each project (excluding Windows Phone 8.0 Silverlight), add an <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.IdentityModel.Clients.ActiveDirectory\/3.5.207081303-alpha\" title=\"ADAL NuGet Package\">ADAL NuGet package<\/a> (currently pre-release). The same NuGet package with the same version should get added to each platform project.<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-20222 size-full\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screen-Shot-2015-07-30-at-12.04.35-pm.png\" alt=\"ADAL-In-Xamarin-Forms-02\" width=\"872\" height=\"582\" \/><\/p>\n<h2>Step 3: Create IAuthenticator Interface<\/h2>\n<p>In your PCL, add a new interface with the Authenticate method. It should return AuthenticateResult from ADAL, which contains the AccessToken and other details that are required for further API calls.<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic interface IAuthenticator\n{\n  Task&lt;AuthenticationResult&gt; Authenticate(string authority, string resource,\u00a0string clientId, string returnUri);\n}\n<\/pre>\n<h2>Step 4: Create IAuthenticator Implementations<\/h2>\n<p>The Authenticate method body is almost the same in each platform. The only change that occurs is different parameters for PlatformParameters, which governs the authentication flow and maintains the context of the app.<\/p>\n<p>Let&#8217;s review the implementations one at a time.<\/p>\n<h3>Android Implementation<\/h3>\n<p>PlatformParameters needs an Activity in Android, and in Xamarin.Forms you can cast Forms.Context to grab the main Activity. The entire implementation in your Android project would look like this:<\/p>\n<pre class=\"lang:csharp decode:true\">\n[assembly: Dependency(typeof(ADALForForms.Droid.Helper.Authenticator))]\nnamespace ADALForForms.Droid.Helper\n{\n  class Authenticator : IAuthenticator\n  {\n    public async Task&lt;AuthenticationResult&gt; Authenticate(string authority, string resource, string clientId, string returnUri)\n    {\n      var authContext = new AuthenticationContext(authority);\n      if (authContext.TokenCache.ReadItems().Any())\n        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);\n\n      var uri = new Uri(returnUri);\n      var platformParams = new PlatformParameters((Activity)Forms.Context);\n      var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);\n      return authResult;\n    }\n  }\n}\n<\/pre>\n<p>Apart from this, you&#8217;ll also need to override the OnActivityResult method in the MainActivity.cs file, which will continue the authentication flow.<\/p>\n<pre class=\"lang:csharp decode:true\">\nprotected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\n{\n  base.OnActivityResult(requestCode, resultCode, data);\n  AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);\n}\n<\/pre>\n<h3>iOS Implementation<\/h3>\n<p>For iOS, PlatformParameters accepts a UIViewController to maintain the context. We can set RootViewController to use it as context, so the implementation on iOS should be as follows:<\/p>\n<pre class=\"lang:csharp decode:true\">\n[assembly: Dependency(typeof(ADALForForms.iOS.Helper.Authenticator))]\nnamespace ADALForForms.iOS.Helper\n{\n  class Authenticator : IAuthenticator\n  {\n    public async Task&lt;AuthenticationResult&gt; Authenticate(string authority, string resource, string clientId, string returnUri)\n    {\n      var authContext = new AuthenticationContext(authority);\n      if (authContext.TokenCache.ReadItems().Any())\n        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);\n\n      var controller = UIApplication.SharedApplication.KeyWindow.RootViewController;\n      var uri = new Uri(returnUri);\n      var platformParams = new PlatformParameters(controller);\n      var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);\n      return authResult;\n    }\n  }\n}\n<\/pre>\n<p>In the case of iOS, we don&#8217;t need to override\/implement any separate method to continue the authentication flow. We should get authResult back whenever the authentication flow completes.<\/p>\n<h3>Windows Phone Implementation<\/h3>\n<p>PlatformParameters doesn&#8217;t need any parameter as such for the Windows Phone app, so we&#8217;ll use the following code to allow us to authenticate with AD:<\/p>\n<pre class=\"lang:csharp decode:true\">\n\n[assembly: Dependency(typeof(ADALForForms.Phone.Helper.Authenticator))]\nnamespace ADALForForms.Phone.Helper\n{\n  class Authenticator : IAuthenticator\n  {\n    public async Task&lt;AuthenticationResult&gt; Authenticate(string authority, string resource, string clientId, string returnUri)\n    {\n      var authContext = new AuthenticationContext(authority);\n      if (authContext.TokenCache.ReadItems().Any())\n        authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);\n\n      var uri = new Uri(returnUri);\n      var platformParams = new PlatformParameters();\n      var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);\n      return authResult;\n    }\n  }\n}\n\n<\/pre>\n<p>Just like Android, Windows Phone needs to handle the continuation after login. This can be done by overriding the OnActivated method in the App.xaml.cs file and calling back to the WebAuthenticationBrokerContinuationHelper.<\/p>\n<pre class=\"lang:csharp decode:true\">\n\nprotected override void OnActivated(IActivatedEventArgs args)\n{\n#if WINDOWS_PHONE_APP\n  if (args is IWebAuthenticationBrokerContinuationEventArgs)\n  {\n    WebAuthenticationBrokerContinuationHelper.SetWebAuthenticationBrokerContinuationEventArgs(args as IWebAuthenticationBrokerContinuationEventArgs);\n  }\n#endif\n  base.OnActivated(args);\n}\n\n<\/pre>\n<h2>Step 5: Call Authenticate() in the Apps<\/h2>\n<p>Now, we need to call the Authenticate method. Let&#8217;s add a new HomePage with a button, which should call the Authenticate method on its click event. Before this, let&#8217;s declare some variables that are required for authentication. To do so, add a new XAML Page and declare your variables for ADAL.<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic static string clientId = &quot;your-client-id&quot;;\npublic static string authority = &quot;https:\/\/login.windows.net\/common&quot;;\npublic static string returnUri = &quot;your-redirct-uri&quot;;\nprivate const string graphResourceUri = &quot;https:\/\/graph.windows.net&quot;;\nprivate AuthenticationResult authResult = null;\n<\/pre>\n<p>Now, we can use the Dependency Service from Xamarin.Forms to locate the Authenticate method in each platform and execute it.<\/p>\n<pre class=\"lang:csharp decode:true\">\nprivate async void Button_OnClicked(object sender, EventArgs e)\n{\n var auth = DependencyService.Get&lt;IAuthenticator&gt;();\n var data = await auth.Authenticate(authority, graphResourceUri, clientId, returnUri);\n var userName = data.UserInfo.GivenName + &quot; &quot; + data.UserInfo.FamilyName;\n await DisplayAlert(&quot;Token&quot;, userName, &quot;Ok&quot;, &quot;Cancel&quot;);\n}\n<\/pre>\n<p>Here, you should have results in the authResult variable. You can use the Access Token from authResult to call any APIs that are secured by Azure Active Directory, e.g., Office 365 and Graph.<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/image00.gif\"><img decoding=\"async\" class=\"alignnone wp-image-20226 size-full\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/image00.gif\" alt=\"ADAL-In-Xamarin-Forms-Last-Image\" width=\"1152\" height=\"720\" \/><\/a><\/p>\n<p><b>Note<\/b>: ADAL used in this blog post is in preview mode. There may be changes by the time it is released.<\/p>\n<p>You can download the sample created for this post, update your\u00a0credentials (e.g. Client Id and Redirect URI), and test the app from <a href=\"https:\/\/github.com\/mayur-tendulkar\/\" title=\"GitHub\" target=\"_blank\">GitHub<\/a>\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Azure Active Directory Authentication Library (aka ADAL) makes authentication with Azure Active Directory a breeze. We&#8217;ve already covered usage of ADAL in various posts on authenticating with Active Directory, adding storage, and adding collaboration (SharePoint) to your mobile apps. ADAL is available for various platforms and supports Xamarin.Android, Xamarin.iOS, and Windows Phone. It&#8217;s easy [&hellip;]<\/p>\n","protected":false},"author":549,"featured_media":20271,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4,16],"class_list":["post-20218","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>The Azure Active Directory Authentication Library (aka ADAL) makes authentication with Azure Active Directory a breeze. We&#8217;ve already covered usage of ADAL in various posts on authenticating with Active Directory, adding storage, and adding collaboration (SharePoint) to your mobile apps. ADAL is available for various platforms and supports Xamarin.Android, Xamarin.iOS, and Windows Phone. It&#8217;s easy [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/20218","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\/549"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=20218"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/20218\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=20218"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=20218"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=20218"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}