Authenticating With Azure Active Directory In Universal Windows Platform Applications

The AAD team are continuing to evolve the samples and NuGet packages that can be referenced when authenticating with Azure Active Directory. In this post I’m going to add authentication to the Windows platform applications using the Active Directory Authentication Library (package id: Microsoft.Indentity.Clients.ActiveDirectory) and the corresponding sample found on github (https://github.com/AzureADSamples/NativeClient-MultiTarget-DotNet). One limitation of the current ADAL is that it doesn’t support Windows Phone 8.0 – adding support for this platform is slightly harder than for universal applications as there is no WebAuthenticationBroker so doing authentication will have to be done via a hosted web browser control within the application.

The first step in adding authentication support across the applications is to a reference to the ADAL package. I’ve added it to the Windows and Windows Phone 8.1 projects, as well as the iOS and Android XForms applications. As the package doesn’t support WP8.0 it can’t be added to either the XForms portable class library, the Core portable class library, nor the Windows Phone 8.0 projects. At this stage we’ll exclude the Mobile Service project as we currently don’t need ADAL there.

Into the RealEstateInspector.Core portable class library I’m going to add a Constants class which contains the various values required when requesting the authorization code and access token using the ADAL.

public static class Constants
{
    public const string ADTenant = “realestateinspector.onmicrosoft.com”;
    public const string ADAuthority=”https://login.windows.net/” + ADTenant;

    public const string ADNativeClientApplicationClientId = “a5a10ee9-f871-4bde-997f-3f1c323fefa5”;

    public const string ADRedirectUri = “http://tba.com”;

    public const string MobileServiceAppIdUri= “https://realestateinspector.azure-mobile.net/login/aad”;
}

Rather than having to duplicate the authentication code between each of the client projects I’m going to create another Shared project called RealEstateInspector.Shared.Client and add a class called AuthenticationHelper. I’ll add a reference to this project to all of the client projects, except the Windows Phone 8.0 project, since this is currently unsupported.

public static class AuthenticationHelper
{

    public static async Task<string> Authenticate()
    {
        try
        {
            var authContext = new AuthenticationContext(Constants.ADAuthority);
            if (authContext.TokenCache.ReadItems().Count() > 0)
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
            var authResult =
                await
                    authContext.AcquireTokenAsync(Constants.MobileServiceAppIdUri,
                    Constants.ADNativeClientApplicationClientId,
                    new Uri(Constants.ADRedirectUri),
#if WINDOWS_PHONE_APP
                    new AuthorizationParameters()
#else
                        new AuthorizationParameters(PromptBehavior.Auto, false)
#endif
                    );
            Debug.WriteLine(authResult != null);

            return authResult.AccessToken;

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            return null;
        }
    }
}

In our Windows platform projects I need to update the AuthenticationClick methods as follows:

private async void AuthenticateClick(object sender, RoutedEventArgs e)
{
    var token = await AuthenticationHelper.Authenticate();
    await CurrentViewModel.LoadPropertyData(token);

}

And I’ve made a simple tweak to the LoadPropertyData method to accept the access token as a parameter.

The last thing to do is in the App.xaml.cs file to add an override to the OnActivated method. Note that this is required due to the differences in the WebAuthenticationBroker implementations between Windows and Windows Phone 8.1.

protected override void OnActivated(IActivatedEventArgs args)
{
    base.OnActivated(args);

#if WINDOWS_PHONE_APP
    if (args is IWebAuthenticationBrokerContinuationEventArgs)
    {
        WebAuthenticationBrokerContinuationHelper.SetWebAuthenticationBrokerContinuationEventArgs(args as IWebAuthenticationBrokerContinuationEventArgs);
    }
#endif

}

At this point whilst we’ve added references to ADAL to the client projects, the only applications that can be run and signed into are the Windows platform applications (Windows and Windows Phone 8.1).

Leave a comment