Azure Active Directory authentication in .NET MAUI

Azure Active Directory authentication in .NET MAUI

13 November 2021

.NET MAUI/Xamarin

Buy Me A Coffee

Hello!

Today, we will create a small mobile application, which requires user authentication, using .NET MAUI.

I hope you already have a valid environment. Read this article on how to set up .NET MAUI.

If you don't have an Azure Active Directory, watch this video on how to set it up:

Azure Active Directory authentication in .NET MAUI

And Azure Active Directory (B2C):

Azure Active Directory B2C authentication in .NET MAUI

So let's start!

  1. Create a new .NET MAUI project.

  2. Install Microsoft.Identity.Client package:
    Microsoft Identity Client Nuget

If the library doesn't work on iOS/MacCatalyst, you can still use .NET MAUI WebAuthenticator.

  1. Create Constants class:

  1. Then modify manifest files.
    For Android open AndroidManifest.xml and add the next activity to the application:

Pay attention that data android:scheme starts with msal.

For iOS add the following code to the Info.plist:

It allows the app to correctly work with Microsoft Authenticator if a user has MFA enabled.

  1. We need to override some methods to receive a callback from the identity server.

For Android open Android/MainActivity.cs and override OnActivityResult method:

You also need to set the activity attribute Exported = true.

For iOS open iOS/AppDelegate.cs and override OpenUrl method:

  1. It's time to create our AuthService:

  1. Now we can prepare the UI to use our AuthService.
    Add login button to your XAML and add Clicked event handler:

We are done. Start the application and check the result.
MAUI Auth

The full code can be found on GitHub.

MauiAuth Blazor sample GitHub.

Buy Me A Coffee

Related:

Drag and Drop any content from a .NET MAUI application

The article demonstrates how to add drag and drop functionality to easily move content from the .NET MAUI application to the operating system.

AppIcon Badge with .NET MAUI

The article demonstrates how to add the AppIcon badge number with .NET MAUI.

An unhandled error has occurred. Reload

🗙