{"id":25814,"date":"2016-05-24T09:00:30","date_gmt":"2016-05-24T16:00:30","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=25814"},"modified":"2016-05-24T09:00:30","modified_gmt":"2016-05-24T16:00:30","slug":"authenticate-mobile-apps-using-microsoft-authentication-library","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/authenticate-mobile-apps-using-microsoft-authentication-library\/","title":{"rendered":"Authenticate Your Mobile Apps Using Microsoft Authentication Library"},"content":{"rendered":"<p>\t\t\t\tEnterprise applications often need to hook into existing infrastructure in mobile apps and many depend on Active Directory for authentication. Microsoft Azure Active Directory, which is a cloud based active directory, provides identity for such mobile apps. In a <a href=\"https:\/\/blog.xamarin.com\/put-adal-xamarin-forms\/\" target=\"_blank\">previous blog post<\/a>, we used Active Directory Authentication Library (ADAL) to authenticate mobile apps with AD. <\/p>\n<p>Microsoft <a href=\"https:\/\/blogs.technet.microsoft.com\/ad\/2016\/03\/31\/microsoft-identity-at-build-2016\/\">recently released a successor<\/a> to this library named Microsoft Authentication Library (MSAL), which simplifies the registration of mobile apps with AD as well as streamlining authentication by handling Microsoft accounts, Azure AD accounts, and Azure AD B2C users with a single programming model. In this blog post, let&#8217;s dive into using MSAL for authenticating a Xamarin.Forms app with AD.<\/p>\n<h2>Step 1: Register Your Mobile App<\/h2>\n<p>The first thing necessary to secure a mobile app with AD is to register it to use AD as an Identity Provider. To register, visit: <a href=\"https:\/\/apps.dev.microsoft.com\">https:\/\/apps.dev.microsoft.com<\/a>. There, you&#8217;ll see current applications using AD, as well as the ability to register new applications.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-25815\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screenshot-2016-05-14-09.41.55.png\" alt=\"MSAL-01-App-Listing\" width=\"840\" height=\"485\" \/><\/p>\n<p>On this page, click on the &#8216;Add an app&#8217; button to register a new application.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-25816\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/Screenshot-2016-05-14-09.42.22.png\" alt=\"MSAL-02-Add-App\" width=\"500\" height=\"161\" \/><\/p>\n<p>Enter a name and click the &#8216;Create application&#8217; button. This will take you to the next page.<\/p>\n<p>On this page, make a note of the Application Id and click on &#8216;Add Platform&#8217; button and select &#8216;Mobile application&#8217; as a platform. You can then add a company or app logo or other details before saving the application.<\/p>\n<h2>Step 2: Set Up the\u00a0Application<\/h2>\n<p>MSAL is supported in Xamarin applications. Create a new Xamarin.Forms application and add the MSAL <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Identity.Client\/1.0.303282006-alpha\" target=\"_blank\">NuGet package<\/a>. If you&#8217;re using Visual Studio to create a Xamarin.Forms applications, a Windows Phone 8.1 project is added automatically, which is not supported by MSAL. This tutorial focuses on using Xamarin.Forms to create iOS, Android, and UWP apps. To correct this, we need to retarget the PCL by editing the .csproj file of the PCL and change the <code>TargetFrameworkProfile<\/code> to <span style=\"text-decoration: underline\"><strong>Profile7<\/strong><\/span>:<\/p>\n<pre class=\"theme:vs2012 lang:c# decode:true\">\nProfile7\n<\/pre>\n<p><em>Note:<\/em> MSAL, as used in this blog post, is still in preview. The code and\/or APIs may change by the time the MSAL NuGet is promoted from prerelease.<\/p>\n<h2>Step 3: Create a Login Page<\/h2>\n<p>Add a Login Page in the PCL project. We&#8217;ll be using a <a href=\"https:\/\/blog.xamarin.com\/customize-your-xamarin-forms-app-with-pages-for-each-platform\/\">PageRenderer<\/a> to create a platform-specific login user interface.<\/p>\n<p>To get started, declare a few static variables in App.cs (or App.xaml.cs if you&#8217;re using a XAML <code>Application<\/code> class) and initialize them for our application to use:<\/p>\n<pre class=\"theme:vs2012 lang:c# decode:true\" title=\"Initialization Code\">\npublic static PublicClientApplication ClientApplication { get; set; }\npublic static string[] Scopes = { \"User.Read\" };\npublic App()\n{\n   ClientApplication = new PublicClientApplication(\"your-app-id\");\n   var content = new Login();\n   MainPage = new NavigationPage(content);\n}\n<\/pre>\n<p>Add a label (<code>WelcomeText<\/code>) and a button (<code>LoginButton<\/code>) to the Login Page. Create an <code>IPlatformParameters<\/code> object to hold platform specific parameters and add an event handler for <code>LoginButton<\/code>. The codebehind for the Login Page should look something like this:<\/p>\n<pre class=\"theme:vs2012 lang:c# decode:true \" title=\"Login Page Code\">\npublic IPlatformParameters PlatformParameters { get; set; }\npublic Login()\n{\n   InitializeComponent();\n   LoginButton.Clicked += LoginButton_Clicked;\n}\nprotected override void OnAppearing()\n{\n   App.ClientApplication.PlatformParameters = PlatformParameters;\n   base.OnAppearing();\n}\nprivate async void LoginButton_Clicked(object sender, EventArgs e)\n{\n   try\n   {\n      AuthenticationResult ar = await App.ClientApplication.AcquireTokenAsync(App.Scopes);\n      WelcomeText.Text = $\"Welcome {ar.User.Name}\";\n   }\n   catch (MsalException ex)\n   {\n      WelcomeText.Text = ex.Message;\n   }\n}<\/pre>\n<p>The <code>AuthenticationResult<\/code> object contains the <code>AccessToken<\/code>, which can later be used for calling any API secured by AD. Next, add a <code>LoginPageRenderer<\/code> to the Android and iOS projects to help the library properly authenticate users.<\/p>\n<pre class=\"theme:vs2012 lang:c# decode:true\" title=\"Login Page Renderer for Android\">\n[assembly: ExportRenderer(typeof(Login), typeof(LoginPageRenderer))]\nnamespace MSALForForms.Droid\n{\n   public class LoginPageRenderer : PageRenderer\n   {\n      private Login _page;\n      protected override void OnElementChanged(ElementChangedEventArgs&lt;Page&gt; e)\n      {\n         base.OnElementChanged(e);\n         _page = e.NewElement as Login;\n         var activity = this.Context as Activity;\n         _page.PlatformParameters = new PlatformParameters(activity);\n      }\n    }\n}\n<\/pre>\n<pre class=\"theme:vs2012 lang:c# decode:true\" title=\"Login Page Renderer for iOS\">\/\/Login Page Renderer for iOS\n[assembly: ExportRenderer(typeof(Login), typeof(LoginPageRenderer))]\nnamespace MSALForForms.iOS\n{\n   class LoginPageRenderer : PageRenderer\n   {\n      Login _page;\n      protected override void OnElementChanged(VisualElementChangedEventArgs e)\n      {\n          base.OnElementChanged(e);\n          _page = e.NewElement as Login;\n      }\n      public override void ViewDidLoad()\n      {\n          base.ViewDidLoad();\n          _page.PlatformParameters = new PlatformParameters(this);\n      }\n   }\n}<\/pre>\n<p>At this stage,\u00a0run the app on a device or simulator to see the results.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-full wp-image-25832\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/MSAL-Screens.gif\" alt=\"MSAL-Screens\" width=\"640\" height=\"360\" \/><\/p>\n<h2>Wrapping Up<\/h2>\n<p>Now that your application user is authenticated with MSAL, you can build apps that consume the Microsoft Graph API, Office 365 APIs, or even ASP.NET WebAPIs&mdash;any endpoint that is secured by AD can now be easily accessed without prompting the user to re-authenticate. For more information on MSAL, <a href=\"https:\/\/blogs.technet.microsoft.com\/ad\/2016\/03\/31\/microsoft-identity-at-build-2016\/\">read the Build 2016 announcement for MSAL<\/a> from the Microsoft Identity team, or <a href=\"https:\/\/github.com\/mayur-tendulkar\/\">download the sample used in this blog post<\/a> to kickstart your next app using AD for user authentication.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Enterprise applications often need to hook into existing infrastructure in mobile apps and many depend on Active Directory for authentication. Microsoft Azure Active Directory, which is a cloud based active directory, provides identity for such mobile apps. In a previous blog post, we used Active Directory Authentication Library (ADAL) to authenticate mobile apps with AD. [&hellip;]<\/p>\n","protected":false},"author":549,"featured_media":39167,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4,16],"class_list":["post-25814","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>Enterprise applications often need to hook into existing infrastructure in mobile apps and many depend on Active Directory for authentication. Microsoft Azure Active Directory, which is a cloud based active directory, provides identity for such mobile apps. In a previous blog post, we used Active Directory Authentication Library (ADAL) to authenticate mobile apps with AD. [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/25814","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=25814"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/25814\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/39167"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=25814"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=25814"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=25814"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}