SPA AngularJS Authentication using Microsoft Azure Active Directory (ADAL)

The goal of this post is to add authentication to a single page application using a free subscription of Microsoft Azure Active Directory , for that we will use the Active Directory Authentication Library (ADAL) for JavaScript.

Microsoft also offers other versions of this library for Windows Phone, Android and iOS applications – all of them also open source.

You can find all the code of the sample application that we will write on my git hub. You can also see a running demo here.

To use the demo you can login with a guest account:

user: guest@softwarejc.onmicrosoft.com
pass: Softwarejc123

Agenda

  • Some details about our sample application
  • Azure: Create a Microsoft Azure Active Directory and add an Application to it
  • How to use ADAL to add Authorization to a AngularJS state
  • How to use ADAL to add Authorization to a WebAPI controller
  • Conslusion

Some details about our sample application

We will add authentication to a very simple application – a list of tasks to do. This application uses SignalR to notify all connected clients when a note was added/removed.

ToDO list - Application architecture

ToDO list – Application architecture

The user will be asked for his user and password when he tries to open a restricted section of the application and all request to the “Authorized” WebAPI controller will return a “401 Unauthorized” error if the user was not identified.

Azure: Create a Microsoft Azure Active Directory and Add an Application to it

We need a Microsoft Azure Active Directory, by default you should have one on your azure account. If you want to create a new one just open Azure > Active Directory and add it.

Create Microsoft Azure Active Directory

Create Microsoft Azure Active Directory

We will need later in our application configuration a tenant ID. The tenant is the Azure Active Directory domain name that shall be call for authentication.

In our example http://softwarejc.onmicrosoft.com

When our Active Directory receives an authentication request he needs to know what to authenticate, therefore we need to create an application in our Active Directory. Just open your Directory > Applications and click “Add”.

Create Active Directory App

Create Active Directory App

Select “Add an application my organization is developing” and give it a name. After the application is created click on configuration and write down the client ID. We will need it later in our application configuration to say Azure which application we want to authenticate.

After you create the application you need to tell azure which source address can ask for authentication, if you try to login from an non authorized address you will see a screen like this one:

AddDebugUrl

Just add your debug URL to the list of Reply URL within your application configuration:

urlAdded

By default our account is assigned to the application that we just created, we can use it to log in. To add user accounts allowed to log in into this application, just create a new user in the active directory and assign it to our application.

In this step we:

  • Created a Microsoft Azure Active Directory, we will need the tenant ID.e.g. http://softwarejc.onmicrosoft.com.
  • Created an application within our Microsoft Azure Active Directory, we will need the client ID. e.g. 280a49e1-ddad-4032-9bcd-2825bqw90330
Azure Authentication diagram

Azure Authentication diagram

How to use ADAL to add Authorization to a AngularJS state

1. Add dependencies

The first step to use ADAL within our SPA is to add the required java script files. They are two, one containing the basic functionality “adal.js” and other which adds an abstraction layer and helpers if you are using AngularJS “adal-angular.js“.

As we use angular, we need both. You can find the libraries here:

If you need the non minimized version you can download it from here: https://github.com/AzureAD/azure-activedirectory-library-for-js

2. Configure the authentication provider

This is the step where we add the tenant id and client id we got on the previous section to the application configuration. Add “AdalAngular” to your module dependencies and initialize it:

adalAuthenticationServiceProvider.init(
    {
	tenant: constants.adalTenant,
        clientId: constants.adalClientId,
        extraQueryParameter: 'nux=1',
        cacheLocation: 'localStorage' // optional cache location default is sessionStorage
    },
$httpProvider);

3. Secure a state or url

To secure a state in your angular application just add “requireADLogin: true” after your list of views.

You can see an example of module configured to work with azure authentication here.

The user will be automatically redirected to the login screen when he tries to access a restricted url, but it is also possible to trigger a login/logout using the “adalAuthenticationService”, just add it to your controller/service and call:

adalAuthenticationService.login();
adalAuthenticationService.logOut();

The library adal-angular puts the authentication state (true/false) and the user profile in the object “$scope.userInfo”. You can find here the user name, email and other information.

How to use ADAL to add Authorization to a WebAPI controller

We already secured our application but in this last step we will also add the ADAL to our WebAPI controllers. As you will see it is extremely easy…

1. Add the attribute “Authorize” to the controller or methods of your controller that you want to authorize.

2. Add the nuget: Microsoft.OWIn.Security.ActiveDirectory

3. Configure ADAL during the application startup:

/// <summary>
/// Configures WindowsAzure Active Directory authentication
/// </summary>
private void ConfigureAuth(IAppBuilder app)
{
    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
       new WindowsAzureActiveDirectoryBearerAuthenticationOptions
       {
           // Azure active directory to use
           Tenant = ConfigurationManager.AppSettings["adal:Tenant"],

           // Active directory application to authenticate 
           TokenValidationParameters = new TokenValidationParameters
           {
               ValidAudience = ConfigurationManager.AppSettings["adal:ClientId"],
           }
       });
}

You can find my Startup.cs here.

Conclusion

Microsoft Azure Active Directory is a great solution for securing our applications, Microsoft did a great job!

Our application and our WebAPI is secured but I have still to learn how to secure a SignalR connection. Maybe some of you has an idea to do it.
If you have read the post please leave a comment, I am sure that you found some mistakes or you would do something different!

Resources:

Introducing ADAL JS v1

Thanks for reading!

2 thoughts on “SPA AngularJS Authentication using Microsoft Azure Active Directory (ADAL)

Your feedback is important...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.