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.
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Xamarin.Forms;
- namespace DevEnvAzure {
- public partial class App Application {
-
- public static string ApplicationID = "----dfc6-2089-4e8c-ssss-8d3591736a96";
-
- public static string tenanturl = "https
-
- public static string ReturnUri = "http//DevEnvAzure.microsoft.net";
-
- public static string GraphResourceUri = "https//graph.microsoft.com";
- public static AuthenticationResult AuthenticationResult = null;
- public App() {
- InitializeComponent();
- MainPage = new DevEnvAzure.Login();
- }
- protected override void OnStart() {
-
- }
- protected override void OnSleep() {
-
- }
- protected override void OnResume() {
-
- }
- }
- }
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).
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http//xamarin.com/schemas/2014/forms" xmlnsx="http//schemas.microsoft.com/winfx/2009/xaml" xmlnslocal="clr-namespaceDevEnvAzure" xClass="DevEnvAzure.Login">
- <StackLayout HorizontalOptions="Center" VerticalOptions="Center" Padding="10" Spacing="10">
- <Button Text="" Clicked="Login_OnClicked" Image="login.png" /> </StackLayout>
- </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
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using System;
- using Xamarin.Forms;
- namespace DevEnvAzure {
- public partial class Login ContentPage {
- public Login() {
- InitializeComponent();
- }
- private async void Login_OnClicked(object sender, EventArgs e) {
- try {
- var data = await DependencyService.Get < IAuthenticator > ().Authenticate(App.tenanturl, App.GraphResourceUri, App.ApplicationID, App.ReturnUri);
- App.AuthenticationResult = data;
- NavigateTopage(data);
- } catch (Exception) {}
- }
- public async void NavigateTopage(AuthenticationResult data) {
- var userName = data.UserInfo.GivenName + " " + data.UserInfo.FamilyName;
- await Navigation.PushModalAsync(new HomePage(userName));
- }
- }
- }
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)
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http//xamarin.com/schemas/2014/forms" xmlnsx="http//schemas.microsoft.com/winfx/2009/xaml" xClass="DevEnvAzure.HomePage">
- <Label Text="" xName="lblname" VerticalOptions="Center" HorizontalOptions="Center" />
- </ContentPage>
Modify the code at the backend file given below.
- using Xamarin.Forms;
- namespace DevEnvAzure {
- public partial class HomePage ContentPage {
- public HomePage(string username) {
- InitializeComponent();
- lblname.Text = " Welcome Mr " + username;
- }
- }
- }
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.
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using System.Threading.Tasks;
- namespace DevEnvAzure {
- public interface IAuthenticator {
- Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri);
- }
- }
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.
- [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.
- using Android.App;
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using System;
- using System.Linq;
- using System.Threading.Tasks;
- using Xamarin.Forms;
- [assembly Dependency(typeof(DevEnvAzure.Droid.Authenticator))]
- namespace DevEnvAzure.Droid {
- class Authenticator IAuthenticator {
- public async Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri) {
- try {
- var authContext = new AuthenticationContext(tenantUrl);
- if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority);
- var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters((Activity) Forms.Context));
- return authResult;
- } catch (Exception) {
- return null;
- }
- }
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using Xamarin.Forms;
- [assembly Dependency(typeof(DevEnvAzure.UWP.Authenticator))]
- namespace DevEnvAzure.UWP {
- public class Authenticator IAuthenticator {
- public async Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri) {
- try {
- var authContext = new AuthenticationContext(tenantUrl);
- if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
- var authResult = await
- authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters(PromptBehavior.Auto, false));
- return authResult;
- } catch (Exception) {
- return null;
- }
- }
- }
- }
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.
- using System;
- using System.Linq;
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using UIKit;
- using Xamarin.Forms;
- using System.Threading.Tasks;
- [assembly Dependency(typeof(DevEnvAzure.iOS.Authenticator))]
- namespace DevEnvAzure.iOS {
- class Authenticator IAuthenticator {
- public async Task < AuthenticationResult > Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri) {
- try {
- var authContext = new AuthenticationContext(tenantUrl);
- if (authContext.TokenCache.ReadItems().Any()) authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority);
- var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController));
- return authResult;
- } catch (Exception) {
- return null;
- }
- }
- }
- }
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.
- Remove all the installed NuGet packages.
- Removing the windows Phone 8.1 project from the solution.
- 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
- Register Identity Provider For New OAuth Application
- OAuth Login Authenticating With Identity Provider In Xamarin.Forms
- Create Azure Mobile Apps Service