{"id":27032,"date":"2016-08-11T13:09:28","date_gmt":"2016-08-11T20:09:28","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=27032"},"modified":"2016-08-11T13:09:28","modified_gmt":"2016-08-11T20:09:28","slug":"authenticating-mobile-apps-with-azure-active-directory-b2c","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/authenticating-mobile-apps-with-azure-active-directory-b2c\/","title":{"rendered":"Authenticating Mobile Apps with Azure Active Directory B2C"},"content":{"rendered":"<p>\t\t\t\tIdentity is a critical component of every mobile app, but it&#8217;s also tricky to get right. As developers, we have many different options in terms of authentication. Creating our own identity solution (with username\/password or email\/password combinations) is one approach. However, this also means that we must handle password reset and 2 Factor Authentication (2FA), not to mention ensuring that our solution is securely storing and handling user credentials. Utilizing social accounts has grown in popularity in recent years, but it&#8217;s not uncommon for users to not have accounts with the social providers you support; some users are also wary of privacy concerns with granting applications social permissions.<\/p>\n<p>Azure Active Directory B2C allows developers to <a href=\"https:\/\/azure.microsoft.com\/en-us\/services\/active-directory-b2c\/\">authenticate users with a single identity management solution<\/a> that supports both social providers (Facebook, Google, Microsoft accounts, Amazon, LinkedIn) as well as local accounts (username\/password or email\/password combinations). As developers, we can focus on building great cross-platform mobile apps without having to worry about the pains that come with identity management (scalability, sign in, sign up, password reset, 2FA, etc.), while still building a flexible solution that works for all of our users, whether they prefer authenticating with local accounts or social providers.<\/p>\n<p>In this blog post, you&#8217;ll learn how to use <a href=\"https:\/\/azure.microsoft.com\/en-us\/services\/active-directory-b2c\/\">Azure Active Directory B2C<\/a> to authenticate users in your mobile apps and even add a cool &#8220;advanced&#8221; identity management feature like 2FA.<\/p>\n<h2>Creating an Azure AD B2C Tenant<\/h2>\n<p>Azure Active Directory B2C is completely cloud-based, which allows it to scale to hundreds of millions of consumer identities. To get started, you will need to have an <a href=\"https:\/\/azure.microsoft.com\/en-us\/documentation\/articles\/sign-up-organization\/\">Azure account<\/a>. Azure B2C is <a href=\"https:\/\/azure.microsoft.com\/en-us\/pricing\/details\/active-directory-b2c\/\">currently available free of charge<\/a>, so you shouldn&#8217;t incur any costs with using Azure B2C at this time. Once you&#8217;ve created an Azure account, we&#8217;re ready to get started creating an Azure B2C tenant.<\/p>\n<h4>1. Create an Azure B2C Tenant<\/h4>\n<p>Visit <a href=\"http:\/\/portal.azure.com\">portal.azure.com<\/a> and click New -&gt; Security + Identity -&gt; Active Directory. A new window will open in the Azure classic portal where we&#8217;ll create our Azure B2C tenant.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27065\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/CreateAzureActiveDirectory.png\" alt=\"Creates an Azure Active Directory B2C instance from the new Azure Portal.\" width=\"558\" height=\"232\" \/><\/p>\n<p>Enter a <strong>Name<\/strong>, <strong>Domain Name<\/strong>, and <strong>Country or Region<\/strong> for your tenant. Be sure to check the option that says <strong>This is a B2C directory<\/strong>. Click the checkmark in the lower righthand corner to create your Azure Active Directory B2C tenant.<\/p>\n<p><strong>Note<\/strong>: Azure B2C is only generally available in North America at this time. For regions outside of North America, <a href=\"https:\/\/azure.microsoft.com\/en-us\/documentation\/articles\/active-directory-b2c-reference-tenant-type\/\">check out this blog post on production-scale vs. preview tenants<\/a>.<\/p>\n<p>You may experience issues creating Azure B2C tenants in countries outside this region.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27067\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/CreateB2CDirectory.png\" alt=\"Create a Azure B2C directory in the classic Azure Portal.\" width=\"398\" height=\"298\" \/><\/p>\n<p>When your tenant finishes deployment, click the tenant name, followed by the <strong>Configure<\/strong> tab, and click <strong>Manage B2C Settings<\/strong>.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27071\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/ManageB2CSettings.png\" alt=\"Opens up B2C settings in the new Azure Portal for easy management.\" width=\"305\" height=\"230.5\" \/><\/p>\n<p>This will open up the new Azure Portal for easier management of our Azure B2C tenant. Click the pin icon to pin the settings to your Azure Dashboard for easy management.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27073\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/PinSettingsToDashboard.png\" alt=\"Pins Azure B2C tenant settings to the Azure Dashboard.\" width=\"432\" height=\"66\" \/><\/p>\n<p>You&#8217;ve just created your first Azure AD B2C tenant! At this time, you can use the classic portal to manage users and groups, configure password reset, and enable company branding features. The new Azure Portal can be used for settings management and application creation.<\/p>\n<h4>2. Register Application<\/h4>\n<p>It&#8217;s time to register an application with the tenant we just created! This will allow our application to authenticate users using Azure AD B2C. In the settings for your B2C tenant (which you have pinned to the <a href=\"http:\/\/portal.azure.com\">Azure Dashboard<\/a>), click <strong>Settings<\/strong>, <strong>Applications<\/strong>, then <strong>Add<\/strong>. Enter an <strong>Application Name<\/strong>, select <strong>Yes<\/strong> for <strong>Include Native Client<\/strong>, and click <strong>Create<\/strong>.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27077\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/CreateAB2CApplication.png\" alt=\"Create an application that will authenticate with this B2C tenant.\" width=\"1007\" height=\"369\" \/><\/p>\n<p>After the application is successfully created, click on the app name and copy the <strong>Application Id<\/strong> field for later user.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27079\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/B2CApplicationDetails.png\" alt=\"Copy the Application ID for the the B2C tenant app you just created.\" width=\"524\" height=\"295\" \/><\/p>\n<h4>3. Create a Sign-Up\/Sign-In Policy<\/h4>\n<p>Policies in Azure AD B2C <a href=\"https:\/\/azure.microsoft.com\/en-us\/documentation\/articles\/active-directory-b2c-reference-policies\/\">describe a consumer identity experience<\/a>, such as sign-up, sign-in, or editing a profile. Each policy type has options that we as developers can configure to achieve our ideal identity experience with options like supported account types, attributes to be collected during sign-up, use of 2FA, login page user interface, as well as the information our stored in authentication tokens for use in our apps. We can create multiple policies, but for this app, we will just create one that handles user sign-up and sign-in flows.<\/p>\n<p>In the Settings for your Azure AD B2C tenant, click <strong>Sign-up or sign-in policies<\/strong>, <strong>Add<\/strong>, and enter a <strong>Name<\/strong> for the policy.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27081\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/AddPolicy.png\" alt=\"Add a sign-up or sign-in policy to our tenant.\" width=\"640\" height=\"236\" \/><\/p>\n<p>For this application, we will be using local accounts to authenticate users. On the <strong>Add Policy blade<\/strong>, click <strong>Identity providers<\/strong>, select <strong>Email sign-up<\/strong>, and click <strong>OK<\/strong>. Let&#8217;s collect some information from our user at sign-up. Click <strong>Select sign-up attributes<\/strong>, select the user information to collect, and click <strong>OK<\/strong>.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-27085\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SelectSignUpAttributes.png\" alt=\"Select sign-up attributes for our B2C tenant.\" width=\"557\" height=\"331\" \/><\/p>\n<p>We want this information to be available for usage in the app, so we need to click the <strong>Select application claims<\/strong> blade, click the information to include in our authentication token, and click <strong>OK<\/strong>. One claim you want to be sure to grab is the <code>Object Id<\/code>, as this is the unique identifier for an authenticated user. Try to keep the number of claims minimal, and only select claims that were selected in the sign-up attributes blade. You can always request this information later using the <a href=\"https:\/\/graph.microsoft.io\/en-us\/\">Microsoft Graph API<\/a>.<\/p>\n<p>Enabling 2 Factor Authentication is as easy as clicking the <strong>Multifactor authentication<\/strong> setting and changing the setting to <strong>On<\/strong>.<\/p>\n<p>Click <strong>Create<\/strong> and our sign-in or sign-up policy will be created! Be sure to note the name of the policy after creation (e.x.: B2C_1_SignInSignUp). In just a few clicks and without writing any code, we just added identity management to our app, complete with 2FA!<\/p>\n<h2>Authenticating iOS, Android, and Windows Apps with Azure AD B2C<\/h2>\n<p>Now that all the server-side configuration is completed on our tenant, let&#8217;s use Azure AD B2C to authenticate users! For authentication, we will be using a library named Microsoft Authentication Library, or MSAL. This library makes it extremely easy to authenticate users using Azure AD, Azure AD B2C, or Microsoft accounts as identity providers in a single library. If you are familiar with ADAL, MSAL will feel right at home. As a convenience, the MSAL NuGet has been already added to each project in the solution. MSAL does not support Windows Phone 8.1, so PCLs will need to remove this target in order to use MSAL.<\/p>\n<h4>1. Create an Authentication Client<\/h4>\n<p><a href=\"https:\/\/github.com\/pierceboggan\/xamarin-blog-samples\/tree\/master\/azure\/azure-ad-b2c\/quickstart\">Download the starter code<\/a>, which contains some boilerplate code and a login screen, and open <code>App.cs<\/code>. Enter your <strong>Client Id<\/strong> and <strong>Policy Name<\/strong> from earlier into the corresponding fields. MSAL will use these to provide the correct authentication flow to the user. We have also created a <code>PublicClientApplication<\/code> and passed in our <strong>Client Id<\/strong>, which is the main class in MSAL for authenticating users.<\/p>\n<p>Open up <code>AppDelegate.cs<\/code> in the iOS project and <code>MainActivity.cs<\/code> in the Android project. MSAL requires that we set the <code>PlatformParameters<\/code> property of the <code>PublicClientApplication<\/code> for iOS and Android. This helps to assist the library in presenting a native web view for users to sign-up or sign-in with, and is <strong>required<\/strong> when using MSAL.<\/p>\n<h4>2. Authenticate Users<\/h4>\n<p>Now that we have successfully created an authentication client, let&#8217;s use it to log the user in. Open up the <code>LoginPage.xaml.cs<\/code> file. When the user clicks the button to log in, the event handler <code>LoginButton_Clicked<\/code> will execute. Under the comment <strong>Step #2<\/strong>, add a call to <code>AcquireTokenAsync<\/code> to authenticate users.<\/p>\n<pre class=\"theme:vs2012 lang:C# decode:true\">\/\/ Authenticate users with Microsoft Authentication Library (MSAL).\nvar authenticationResult = await App.AuthenticationClient.AcquireTokenAsync(App.Scopes,\n    \"\",\n    UiOptions.SelectAccount,\n    string.Empty,\n    null,\n    App.Authority,\n    App.SignUpSignInPolicy);\n\/\/ Navigate users into the main portion of our app.\nawait Navigation.PushAsync(new AuthenticationSuccessfulPage(authenticationResult));\n<\/pre>\n<p>This will present a web view to the user. If the user has an account, he can log in; if not, he can create an account using this flow. It&#8217;s worth noting that you don&#8217;t have to use a web view for authentication; you may create your own user interface for this flow and pass the information back to MSAL.<\/p>\n<p>After successful login, users are taken to the main portion of the application, <code>AuthenticationSuccessfulPage<\/code>. Because we are now authenticated, we have access to the authentication token, as well as information like the user id. Let&#8217;s display that information to the user by adding the following code under the <strong>Step #3<\/strong> comment in <code>AuthenticationSuccessfulPage.xaml.cs<\/code>.<\/p>\n<pre class=\"theme:vs2012 lang:C# decode:true\">UserId = $\"User Id: {authenticationResult.User.UniqueId}\";\nExpiresOn = $\"Token Expires {authenticationResult.ExpiresOn.ToString()}\";\n<\/pre>\n<h4>3. Re-authenticate Users Silently<\/h4>\n<p>Authentication tokens only last for a short period of time, and we want to ensure that users can seamlessly use our application without having to re-authenticate. The MSAL library has a great method named <code>AcquireTokenSilently<\/code>, which will attempt to refresh the user token without requiring the user to log back in. Under the Step #4 comment in the <code>AuthenticationSuccesfulPage.xaml.cs<\/code> file, add the following code to refresh the user&#8217;s token.<\/p>\n<pre class=\"theme:vs2012 lang:C# decode:true\">await App.AuthenticationClient.AcquireTokenSilentAsync(App.Scopes, \n    string.Empty,\n    App.Authority, \n    App.SignUpSignInPolicy, \n    false);\n<\/pre>\n<p>In the event that we&#8217;re unable to successfully refresh the token, we present the <code>LoginPage<\/code> to the user to re-authenticate.<\/p>\n<p>Build the app, and you&#8217;ll see a rich sign up and sign in experience with local accounts powered by Azure Active Directory B2C. Users signing up are prompted to verify their email address with a code, create strong passwords, enter information we asked for in our policy, and even verify their phone number for 2FA. Users signing in will be required to enter their credentials as well as enter the code that Azure Active Directory B2C automatically texts the user to authenticate with for maximum security, without any additional effort required from you.<\/p>\n<p>&nbsp;<\/p>\n<table align=\"center\">\n<tbody>\n<tr>\n<td><div style=\"width: 269px;\" class=\"wp-video\"><video class=\"wp-video-shortcode\" id=\"video-27032-1\" width=\"269\" height=\"478\" preload=\"metadata\" controls=\"controls\"><source type=\"video\/mp4\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SignInB2C1.mp4?_=1\" \/><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SignInB2C1.mp4\">https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SignInB2C1.mp4<\/a><\/video><\/div><\/td>\n<td><div style=\"width: 269px;\" class=\"wp-video\"><video class=\"wp-video-shortcode\" id=\"video-27032-2\" width=\"269\" height=\"478\" preload=\"metadata\" controls=\"controls\"><source type=\"video\/mp4\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SignUpB2C2.mp4?_=2\" \/><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SignUpB2C2.mp4\">https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/SignUpB2C2.mp4<\/a><\/video><\/div><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<h2>Wrapping Up<\/h2>\n<p>Azure Active Directory B2C is a <a href=\"https:\/\/azure.microsoft.com\/en-us\/services\/active-directory-b2c\/\">robust, scalable single identity management solution<\/a> capable of handling both local and social accounts. In this blog post, we used Azure AD B2C to authenticate users in our mobile apps for iOS, Android, and Windows, and even took advantage of some &#8220;advanced&#8221; identity management features such as 2 Factor Authentication. To learn more about Azure Active Directory B2C, visit the <a href=\"https:\/\/azure.microsoft.com\/en-us\/documentation\/services\/active-directory-b2c\/\">documentation portal<\/a> or <a href=\"https:\/\/github.com\/pierceboggan\/xamarin-blog-samples\/tree\/master\/azure\/azure-ad-b2c\">download my sample on using Azure AD B2C to authenticate users in Xamarin apps<\/a>.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Identity is a critical component of every mobile app, but it&#8217;s also tricky to get right. As developers, we have many different options in terms of authentication. Creating our own identity solution (with username\/password or email\/password combinations) is one approach. However, this also means that we must handle password reset and 2 Factor Authentication (2FA), [&hellip;]<\/p>\n","protected":false},"author":546,"featured_media":39167,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4],"class_list":["post-27032","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Identity is a critical component of every mobile app, but it&#8217;s also tricky to get right. As developers, we have many different options in terms of authentication. Creating our own identity solution (with username\/password or email\/password combinations) is one approach. However, this also means that we must handle password reset and 2 Factor Authentication (2FA), [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/27032","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\/546"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=27032"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/27032\/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=27032"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=27032"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=27032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}