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:

Extend .NET MAUI application with iOS Extensions

Extend the .NET MAUI application with iOS App Extension in 5 steps.

Prepare .NET MAUI application with CommunityToolkit.MAUI to release

The article describes how to configure .NET MAUI CommunityToolkit to avoid crashes at runtime.

An unhandled error has occurred. Reload

🗙