Top

Use Microsoft Authentication Library(MSAL) in Xamarin.Forms

Use Microsoft Authentication Library(MSAL) in Xamarin.Forms

INTRODUCTION

 

Most users prefer to login with Facebook, Microsoft, Google or Twitter than using registration forms. That’s why it’s important
to know the options and what each one of the authentication libraries offer us.

Let’s talk about Microsoft Authentication Library (MSAL), Perhaps, at user level is not very well known but at the business one is the most important.
Many companies around the world have their employees registered in Active Directory (AD) and MSAL offers us the chance to employees with
your business emails can access the applications.

 

Note: More than 65% of users prefer to use login with providers than to use our registration form.

 

PLATFORMS

 

MSAL is available for Android , iOS , Java , Python, Angular , NodeJS , PHP , JS and every .NET platform (UWP,Xamarin and .NET Core).

 

 

EASY IMPLEMENTATION

 

As a developer I’ve had to implement different auth libraries from the most common providers but in my opinion MSAL is the most easily implemented and if
we talk about Xamarin.Forms, MSAL has no rival. In less than 10-15 minutes you have it working in Xamarin.Forms for all platforms (Android, iOS and UWP).

 

Init library

public static IPublicClientApplication PCA = null;
public App()
{
    PCA = PublicClientApplicationBuilder.Create(ClientID)
        .WithRedirectUri($"msal{App.ClientID}://auth")
        .Build();

    MainPage = new NavigationPage(new UserDetailsClient.MainPage());
}

 

 

Log-in

public async Task SignInAsync()
{
    AuthenticationResult authResult = null;
    IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync();


    // let's see if we have a user in our belly already
    try
    {
        IAccount firstAccount = accounts.FirstOrDefault();
        authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
                                .ExecuteAsync();
        await RefreshUserDataAsync(authResult.AccessToken).ConfigureAwait(false);
        Device.BeginInvokeOnMainThread(() => { btnSignInSignOut.Text = "Sign out"; });
    }
    catch (MsalUiRequiredException ex)
    {
        try
        {
            authResult = await App.PCA.AcquireTokenInteractive(App.Scopes)
                                        .WithParentActivityOrWindow(App.ParentWindow)
                                        .ExecuteAsync();

            await RefreshUserDataAsync(authResult.AccessToken);
            Device.BeginInvokeOnMainThread(() => { btnSignInSignOut.Text = "Sign out"; });
        }
        catch (Exception ex2)
        {

        }
    }
}

 

 

Log-out

public async Task SignOutAsync()
{
    IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync();

    try
    {
        while (accounts.Any())
        {
            await App.PCA.RemoveAsync(accounts.FirstOrDefault());
            accounts = await App.PCA.GetAccountsAsync();
        }

        slUser.IsVisible = false;
        Device.BeginInvokeOnMainThread(() => { btnSignInSignOut.Text = "Sign in"; });

    }
    catch (Exception ex)
    {

    }
}

 

 

GET DATA

public async Task RefreshUserDataAsync(string token)
{
    //get data from API
    HttpClient client = new HttpClient();
    HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
    message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
    HttpResponseMessage response = await client.SendAsync(message);
    string responseString = await response.Content.ReadAsStringAsync();
    if (response.IsSuccessStatusCode)
    {
        //Set data to view
    }
    else
    {
        await DisplayAlert("Something went wrong with the API call", responseString, "Dismiss");
    }
}

 

With these three methods we would already have everything we need to implement auth in
any app.

 

 

AUTOLOGIN AND LOGIN SHARED BETWEEN APPS

 

MSAL offers the possibility of using a silent token if the user has been previously logged by calling a single method.

Another strong point of using MSAL is the possibility to share the Log-in in different Apps. What does this mean? If you are logged into any app that uses MSAL, such as
for example Outlook , if you ask the user to login, the user will not have to enter his password again.

 

 

 

SOURCE CODE AND INFORMATION

 

The source code I used is published here. I have followed the official Microsoft documentation that you can find here.

In the next months we will publish a related video.

 

If you have problem with my example, do not hesitate to send your comments and I will respond quickly.

Miguel Ángel Barrera Muñoz
No Comments

Post a Comment