As I’ve previously blogged, I created a Xamarin Forms application to submit pictures of my receipts to the company I work for. But if I’d publish the app in that state, the whole world could send in receipts on my behalf. So I needed to add authentication. Because the company uses Office 365, I’d decided to add Azure Active Directory.

There are a lot of resources about Adal (Active Directory Authentication Library) Some call it Azure Adal.NET

You can read about it on the Github page

It is also very clear in the that you should in fact upgrade to MSAL.Net

MSAL.NET is the new authentication library to be used with the Microsoft identity platform”

Searching for Xamarin.Forms and Msal.Net did not gave me that much options, so I decided to blog about it.

MSAL stands for MicroSoft Authentication Library. The Github is

It’s for Oauth2 and OpenID connect.

I started with adding an application registration in the azure portal under azure active directory at “app registrations”

I switched to “Single tenant” at the authentication tab/page to make sure that only people from within Partech are allowed.

Further more you need to write down the app (client) id and the directory (tenant) id.

Next was the code integration:

1. add nuget ‘Microsoft.Identity.Client’ to the Xamarin shared app

2. make sure your app.xaml.cs looks like this:

public static IPublicClientApplication PCA;
private const string applicationClientId = "clientidhere";
public static string[] Scopes = { "User.Read" };
public static string Username = string.Empty;

public static object ParentWindow { get; set; }

public App()
	PCA = PublicClientApplicationBuilder.Create(applicationClientId)
		.WithTenantId("tenantid here")


	MainPage = new MainPage();

3. to the mainpage I added an override of OnAppearing which called an async CheckAuth

4. add this code to checkauth:

AuthenticationResult authResult = null;
IEnumerable accounts = await App.PCA.GetAccountsAsync();
	IAccount firstAccount = accounts.FirstOrDefault();
	authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
catch (MsalUiRequiredException ex)
		authResult = await App.PCA.AcquireTokenInteractive(App.Scopes)
	catch (Exception ex2)
		DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss").RunSynchronously();

if (authResult != null)
	await GetHttpContentWithTokenAsync(authResult.AccessToken);

5. for the rest of the code to retrieve the users given name, surname etc. you should check the GitHub link I mentioned previously.

To do more with azure AD use the Graph explorer

Good luck coding!

Post on LinkedIn