Azure Active Directory Login In Xamarin.Forms

Introduction

Microsoft Azure Active Directory (Azure AD) is required to add authentication and authorization to our Web, mobile application and Web APIs. In this article, I have explained how to create/implement Azure Active Directory authentication login, using Xamarin.Forms.

I have seen many articles for the process of moving the management experience for all Azure Services from the ‘classic’ portal here. I am showing new portal here for Azure AD Application creation and user creation.


Azure Subscription Login

The new Azure portal is that you don’t need an Azure subscription to use it. You and other administrators in your organization can manage your tenant in the new portal without your need to get and manage to an Azure subscription. You can directly sign -in as usual with your work or school account.



Azure Active Directory Application creation

I will show the steps given below for the application's creation, user creation and permission configuration. While implementing mobile application, we need Client ID, tenant, return URL, so here I will show how to get all the configuration information from the steps given below.

Step 1

App Registration

Login to Microsoft Azure portal and choose Azure Active Directory from the sidebar.


Under Manage, select App Registration, click on + Add button.

Provide the details given below, name for the application, select the application type as Native (Mobile Application) or Web app/API and to sign in, enter your application URL and click Create.


Step 2

App Required Permissions

We need to give the permission to access the application from mobile or Web, so follow the steps given below for grand permission. Select newly created Application => select Required Permission => Click Grand permission.


Step 3

Create new user

Create the user to access the application. Choose Azure Active Directory from the sidebar. Select Users and groups. Select All Users. Click on +Add and provide the user details, as shown below, where there is name of the user, user name (Email Id).


Step 4

Get Client ID and Redirect URL

The Client Id is a unique aidentifier for our application. We need client Id to implement Azure AD authentication in the mobile application, so you can follow the steps given below to get client Id. Choose Azure Active Directory from the sidebar. Select App registrations. Select newly created application. Click property and use application Id as a client ID.

Click redirected URL under settings and get redirected URL/ update redirected URL.

 

Step 5

Get Tenant

We already need to register our application in a Azure AD tenant. We need tenant ID to implement AD authentication in mobile application. You can follow the steps given below to get tenant Id.


Choose Azure Active Directory from the sidebar, select Properties and use Directory ID as tenant ID.

Implement Xamarin.Forms Application

After completing your Azure app registration, you can start the steps given below to create Xamarin Application with Login AD Authentication.


Step 1

Create New Xamarin Forms Application

Let's start creating new Xamarin Forms Project in Visual Studio. Open Run âž” Type Devenev.Exe and enter âž” New Project (Ctrl+Shift+N)âž” select Blank Xamarin.Forms Portable template.


It will automatically create multiple projects like Portable, Android, iOS and UWP. First, we will start to edit the portable project, followed by platform specific project.

Step 2

Install Microsoft ActiveDirectory nuget Package

Microsoft ADAL provides Xamarin Portable Class Library with an easy to use authentication functionality for.NET client on various platforms including UWP, Xamarin iOS and Xamarin.Android. You can get more info( https//www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/)

To implement Azure active directory login, we need to install Active Directory Authentication Library, I will show the steps given below to install ADAL library.

Select Solution => Right Click Manage nuget Packages for Solution => Search “Microsoft IdentityModel” => Select Microsoft.IdentityModel.Clients.ActiveDirectory => Select all Project => Click on Install


Step 3

Azure AD Configuration (App.xaml.cs)

I have added Azure configuration like ApplicationID, tenantUrl, returnURL and GraphresourceURL in APP.xaml.cs.

In portable project, open App.xaml.cs, update all the configuration.

  1. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using Xamarin.Forms;  
  7. namespace DevEnvAzure {  
  8.     public partial class App Application {  
  9.         // update your Application ID or client ID  
  10.         public static string ApplicationID = "----dfc6-2089-4e8c-ssss-8d3591736a96";  
  11.         //modify your Azure tenant  
  12.         public static string tenanturl = "https//login.microsoftonline.com/<Azure Tenant >  
  13.         //Update your return url  
  14.         public static string ReturnUri = "http//DevEnvAzure.microsoft.net";  
  15.         //No need to change  
  16.         public static string GraphResourceUri = "https//graph.microsoft.com";  
  17.         public static AuthenticationResult AuthenticationResult = null;  
  18.         public App() {  
  19.             InitializeComponent();  
  20.             MainPage = new DevEnvAzure.Login();  
  21.         }  
  22.         protected override void OnStart() {  
  23.             // Handle when your app starts  
  24.         }  
  25.         protected override void OnSleep() {  
  26.             // Handle when your app sleeps  
  27.         }  
  28.         protected override void OnResume() {  
  29.             // Handle when your app resumes  
  30.         }  
  31.     }  
  32. }  

Step 3

Create Login Page (Login.Xaml)

I have created quick and simple login screen. You can modify, as per your requirement.

Right click on Portable Class Library âž” Add New Item âž” Select XAML Page(Login).

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http//xamarin.com/schemas/2014/forms" xmlnsx="http//schemas.microsoft.com/winfx/2009/xaml" xmlnslocal="clr-namespaceDevEnvAzure" xClass="DevEnvAzure.Login">  
  3.     <StackLayout HorizontalOptions="Center" VerticalOptions="Center" Padding="10" Spacing="10">  
  4.         <Button Text="" Clicked="Login_OnClicked" Image="login.png" /> </StackLayout>  
  5. </ContentPage>  

Step 4

Login Click Event (Login.Xaml.cs)

Add LoginClick event in the login page code at the backend file and if the login is succeed, as the page navigates to the home page

  1. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  2. using System;  
  3. using Xamarin.Forms;  
  4. namespace DevEnvAzure {  
  5.     public partial class Login ContentPage {  
  6.         public Login() {  
  7.             InitializeComponent();  
  8.         }  
  9.         private async void Login_OnClicked(object sender, EventArgs e) {  
  10.             try {  
  11.                 var data = await DependencyService.Get < IAuthenticator > ().Authenticate(App.tenanturl, App.GraphResourceUri, App.ApplicationID, App.ReturnUri);  
  12.                 App.AuthenticationResult = data;  
  13.                 NavigateTopage(data);  
  14.             } catch (Exception) {}  
  15.         }  
  16.         public async void NavigateTopage(AuthenticationResult data) {  
  17.             var userName = data.UserInfo.GivenName + " " + data.UserInfo.FamilyName;  
  18.             await Navigation.PushModalAsync(new HomePage(userName));  
  19.         }  
  20.     }  
  21. }  

Step 4

Create Home page

I have created quick and simple home screen. You can modify, as per your requirement

Right click on Portable Class Library âž” Add New Item âž” Select XAML Page(Homepage)

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http//xamarin.com/schemas/2014/forms" xmlnsx="http//schemas.microsoft.com/winfx/2009/xaml" xClass="DevEnvAzure.HomePage">  
  3.     <Label Text="" xName="lblname" VerticalOptions="Center" HorizontalOptions="Center" />   
  4. </ContentPage>  

Modify the code at the backend file given below.

  1. using Xamarin.Forms;  
  2. namespace DevEnvAzure {  
  3.     public partial class HomePage ContentPage {  
  4.         public HomePage(string username) {  
  5.             InitializeComponent();  
  6.             lblname.Text = " Welcome Mr " + username;  
  7.         }  
  8.     }  
  9. }  

Step 5

Create Authentication Interface

In a portable project, add a new interface for Authentication method. The authentication method will return Authentication result from ADAL, which contains the AccessToken and the user details .

Right click on PCL project and select Interface => name as IAuthenticator.cs => Click OK.

  1. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  2. using System.Threading.Tasks;  
  3. namespace DevEnvAzure {  
  4.     public interface IAuthenticator {  
  5.         Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri);  
  6.     }  
  7. }  

Step 6

Implement Platform Specific Dependency Service

We need to implement platform specific dependency Services for login authentication.

The code given below is Xamarin.Forms DependencyService, which maps Authenticator.

  1. [assembly Dependency(typeof(DevEnvAzure.Droid.Authenticator))]  

Android Application

Add Authenicator clsss in Xamarin Android Application.

Right click on Android Project => Select Class=> Name as an Authenticator.

  1. using Android.App;  
  2. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  3. using System;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. [assembly Dependency(typeof(DevEnvAzure.Droid.Authenticator))]  
  8. namespace DevEnvAzure.Droid {  
  9.     class Authenticator IAuthenticator {  
  10.         public async Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri) {  
  11.             try {  
  12.                 var authContext = new AuthenticationContext(tenantUrl);  
  13.                 if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority);  
  14.                 var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters((Activity) Forms.Context));  
  15.                 return authResult;  
  16.             } catch (Exception) {  
  17.                 return null;  
  18.             }  
  19.         }  
  20.     }  
  21. }  

Now, run your Application and see the result given below.


UWP Application

Add Authenicator clsss in Xamarin UWP Application

Right click on UWP Project => select Class=> Name as an Authenticator.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  7. using Xamarin.Forms;  
  8. [assembly Dependency(typeof(DevEnvAzure.UWP.Authenticator))]  
  9. namespace DevEnvAzure.UWP {  
  10.     public class Authenticator IAuthenticator {  
  11.         public async Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri) {  
  12.             try {  
  13.                 var authContext = new AuthenticationContext(tenantUrl);  
  14.                 if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);  
  15.                 var authResult = await  
  16.                 authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters(PromptBehavior.Auto, false));  
  17.                 return authResult;  
  18.             } catch (Exception) {  
  19.                 return null;  
  20.             }  
  21.         }  
  22.     }  
  23. }  

Now, run your Application and see the result given below.


iOS Application

Add Authenicator clsss in Xamarin iOS Application

Right click on iOS Project => Select Class=> Name it as an Authenticator.

  1. using System;  
  2. using System.Linq;  
  3. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  4. using UIKit;  
  5. using Xamarin.Forms;  
  6. using System.Threading.Tasks;  
  7. [assembly Dependency(typeof(DevEnvAzure.iOS.Authenticator))]  
  8. namespace DevEnvAzure.iOS {  
  9.     class Authenticator IAuthenticator {  
  10.         public async Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri) {  
  11.             try {  
  12.                 var authContext = new AuthenticationContext(tenantUrl);  
  13.                 if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority);  
  14.                 var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController));  
  15.                 return authResult;  
  16.             } catch (Exception) {  
  17.                 return null;  
  18.             }  
  19.         }  
  20.     }  
  21. }   

Now, run your application and see the result given below.


Issues and Solution

I have shared some implementation, development issues, and solutions, which are given below.


Error: cannot install Package Microsoft.IdentityModel.Client.ActiveDirectory

While trying to add NuGet package for Azure Active Directory ('Microsoft.IdentityModel.Clients.ActiveDirectory 3.13.8') , it is possible that you will receive an error complaining that the package does not contain any assembly references which are compatible with the targets of your PCL project. For your reference, the error is given below.

Error

Cannot install the package 'Microsoft.IdentityModel.Clients.ActiveDirectory 3.13.8'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with the framework. For more information, contact the package author.

Solution

ADAL does not support Windows phone 8.1 version, so we need to follow the steps given below to resolve above shown issue.

  1. Remove all the installed NuGet packages.
  2. Removing the windows Phone 8.1 project from the solution.
  3. Remove the target platform from the PCL project.

Step 1

Remove all installed NuGet packages

Go to solution > Right Click on Manage NuGet Packages > Click on Installed tab > Uninstall all the installed packages like (Including Xamarin.Form etc ) .

If you are not uninstalling the package and trying to change the targeted platforms by removing the target Windows Phone 8.1, you will get an error.


Step 2

Remove the Windows 8.1 project from Solution

ADAL does not support Windows phone 8.1, so you need to remove Windows 8.1 project from the solution. Only removing Windows Phone 8.1 project from your solution will not resolve this issue. You still need to follow the next steps as well.

Step 3

Remove target platform from the PCL project

Right click on your PCL project > Click Properties > Go to the tab “Library” > You can see the list of the targeted platforms > Press the button “Change” > uncheck the target “Windows phone 8.1” and “ Windows phone Silvelight 8” > Press OK button.

 Wait for few seconds, the dialog will be gone and the target is removed from the PCL project.


Now, you are able to install ADAL NuGet package from your solution.


Error

Micrsoft.identityModel.Clients.ActiveDirectory.AdalServiceExceptionAADSTS65005The Client application has requested an access to the resource ‘https//graph.microsoft.com’. The request has failed because the client has no specific resource in its requredResourceAccss list. If you get the error given above, it means try the solution given below.


Solution

You have missed granting grand permission to your Application, so we need to give permission to access the application from mobile or the Web, so follow the steps given below for grand permission. Select newly created application and select Required Permission, followed by clicking on Grand permission.


Related Articles

  1. Register Identity Provider For New OAuth Application
  2. OAuth Login Authenticating With Identity Provider In Xamarin.Forms
  3. Create Azure Mobile Apps Service