Introduction
In this article, I will explain about .NET MAUI Authentication implementation using Visual Studio 2022. Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against an authority. The entity that submitted the credentials is considered an authenticated identity if the credentials are valid. Once an identity has been established, an authorization process determines whether that identity has access to a given resource or not and Microsoft Data sync Framework has built-in support for any authentication provider that uses a Json Web Token (JWT) within a header of the HTTP transaction. This application uses the Microsoft Authentication Library (MSAL) to request such a token and authorize the signed-in user to the backend service.
Although we use Microsoft Entra ID for authentication, you can use any authentication library you wish with Azure Mobile Apps.
There are many ways to do authentication using .NET MAUI
- Basic: This is used when authentication is done for both personal and corporate accounts without using a broker therefore, a personal account means a Microsoft personal account such as Outlook, etc.
- With Broker: This is intended for corporate accounts where an extra layer of security is added by using Authenticator/Broker. This is useful for MFA and is required to comply with other security policies such as conditional access.
- B2C: This is used when the end user can log in using OAuth2 credentials such as Google, Facebook, etc. This does not support the broker.
Authentication using .NET MAUI
Step 1
Create a new project in Visual Studio 2022 and select the app option under the multiplatform on the left side panel. After that, you need to click the .NET MAUI App with C# option and click the continue button.
Step 2
On the next page, you need to select the .Net framework version 6.0 and click the continue button.
Step 3
On the next page, You need to provide your project name and solution name along with your location and click on Create button
Step 4
The next step is to download the NuGet Package Microsoft Identity Web & Microsoft Identity Client
1. Download Microsoft.Identity.Web from NuGet Package Manager
dotnet add package Microsoft.Identity.Web --version 2.17.0
This package enables ASP.NET Core web apps and web APIs to use the Microsoft identity platform (formerly Azure AD v2.0). This package is specifically used for web applications, which sign-in users, and protected web APIs, which optionally call downstream web APIs.
2. Download Microsoft.Identity.Web from NuGet Package Manager
dotnet add package Microsoft.Identity.Client --version 4.59.0
it will help you to access MSAL.NET make it easy to obtain tokens from the Microsoft identity platform for developers signing in users with work and school accounts Microsoft personal accounts and social identities via Azure AD B2C. These tokens provide access to Microsoft Cloud API and any other API secured by the Microsoft identity platform. This version supports adding authentication functionality to your .NET based clients .NET MAUI, .NET Framework .NET MAUI, Xamarin iOS, Xamarin Android and UWP.
Step 5
The next step is to create a new configuration string following with Azure details and Codesign Entitlement.
Therefore, the following
public string[] Scopes => new string[] { "https://xxxxxxxxx//user_impersonation" };
public string ClientId => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public string Authority => "https://login.microsoftonline.com/xxxxxxxxxx/saml2";
public string AdAuthRedirectUrl => "xxxxxxxxx://auth";
public string CodesignEntitlement => "Buddle ID";
Step 6
The next step is to create a new class for connection with Azure like AzureAdAuthService.cs file and define the PublicClientApplicationBuilder in the constructor.
using Microsoft.Identity.Client;
namespace ContextMenu
{
public class AzureAdAuthService
{
private readonly IPublicClientApplication authenticationClient;
public string[] Scopes => new string[] { "https://xxxxxxxxx//user_impersonation" };
public string ClientId => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public string Authority => "https://login.microsoftonline.com/xxxxxxxxxx/saml2";
public string AdAuthRedirectUrl => "xxxxxxxxx://auth";
public string CodesignEntitlement => "Buddle ID";
public AzureAdAuthService()
{
authenticationClient = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(Authority)
.WithRedirectUri(AdAuthRedirectUrl)
.WithIosKeychainSecurityGroup(CodesignEntitlement)
.Build();
}
public async Task<AuthenticationResult> LoginAsync(CancellationToken cancellationToken)
{
AuthenticationResult result = null;
result = await authenticationClient.AcquireTokenInteractive(Scopes)
.WithParentActivityOrWindow(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity)
.WithPrompt(Prompt.ForceLogin)
.ExecuteAsync(cancellationToken);
return result;
}
}
}
Step 7
The next step is to define authentication in the source page and create the new event to define AzureAdAuthService to connect with MSAL.NET.
namespace ContextMenu;
using System.IdentityModel.Tokens.Jwt;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void ConnectionClicked(System.Object sender, System.EventArgs e)
{
PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
if (status == PermissionStatus.Granted)
{
var authService = new AzureAdAuthService();
var result = await authService.LoginAsync(CancellationToken.None);
var token = result?.AccessToken;
if (token != null)
{
var handler = new JwtSecurityTokenHandler();
var data = handler.ReadJwtToken(token);
var claims = result.ClaimsPrincipal.Claims.ToList();
if (data != null)
{
var EmailID = claims.FirstOrDefault(x => x.Type.Equals("preferred_username"))?.Value;
var UserName = claims.FirstOrDefault(x => x.Type.Equals("name"))?.Value;
}
}
}
}
}
Conclusion
Hopefully, this article has given you sufficient information for you to Implement the Azure AD Authentication Connection using .Net MAUI and run the app on both Android/iOS. Feel free to leave a comment if you would like me to further elaborate on anything within this article.