Integrating your SPA with Azure AD13 min read


As a user I want to be able to login to system using my work account

This is one of the most used lines in a user story in almost every project’s backlog. However, in some cases it might be the case that you are responsible to decide which authentication mechanism to be used.

The source code for this post can be found on my GitHub repository.

You might have to use Azure Active Directory (AD) and if that’s the case this post will help you to get up to speed with that process. The assumption is that you have a single page application (SPA) and are using ASP.Net Core Web API as your supporting back-end.

Also I will assume that you already have an Azure AD setup and have created an application with return URL http://localhost:4200. If you do not know how to do that please read this article.

Note: the project structure I use here is not best practice and is only used to show you how you can utilise Azure AD as your authentication mechanism. However, I’ve used it in a large project and it has served me well in the development productivity.

Setting up the projects

We will need two projects, one for the APIs and one for the client side. I will use Angular CLI for the client side. So let’s create them. I will use Visual Studio 2017 but feel free to use Visual Studio Code or even a console.

After creating your solution, you will need to create a web API project targeting .NET CORE 2.0. Do not select an authentication scheme at this time since we will configure it shortly. Then create an empty web project and use whatever name you like. For now I’ve used API and Web as my preferred names.

Your project structure should look something like this by now:

Configuring the required services

Once done open your Startup.cs file and navigate to ConfigureServices method. If you are wondering why please read my previous post on the changes in ASP.NET Core 2.0.

Before we can setup our authentication we need to setup our configuration with the values you gathered when setting up Azure AD and the application. Open your appsettings.json and add these lines:

Note: remember to replace the application and tenant Id with yours.

Now navigate to ConfigureServices method and add the authentication and authorisation services options as below:

To give you a bit of intro on the code, we first retrieve the Azure AD configuration. Afterwards, we get an instance of ILogger for logging purposes (you can skip this part if you like but you have to remove it from event handler as well).

That done, we add the authentication to services instance and set a default scheme (in this case I am using JwtBearer). Then have to configure our preferred option. This part is very straight forward so I am not going through the whole code.

* You can find the code for MyJwtBearerEvents here.

It’s time to let ASP.NET Core know it should use authentication. This is an important step since without it the whole setup won’t work. Head to Configure method and add the middle ware:

We’re done with configuration at this point, time to secure our API. I’ve got a ValuesController which I will add the Auhorize attribute to it:

Creating the client side

Alright, now that the server side is secured, let set up our client side to use Azure AD authentication.

We will start by initialising our project. Head to Web folder and open a console (you will need to have nodejs, npm and AngularCLI installed globally). Run this command to create an application:

Now go to spa folder and cut and paste everything to root of the Web folder (this is for simplicity and ease of use). Lets add all the required packages by adding them to package.json file. Open it up and add these lines to dependencies section:

The first package is a wrapper around adal which is used to authenticate to Azure Active Directory. I will show you how we use it later.

Now run:

Once finished, we need to define some routes for the application so we can secure a particular one. Protecting routes is a very common task when building applications, as we want to prevent our users from accessing areas that they’re not allowed to access, or, we might want to ask them for confirmation when leaving a certain area. Angular’s router provides a feature called Navigation Guards that try to solve exactly that problem.

Here is how our guard looks like:

As you can see I am using one of the packages we added earlier which helps configure our application to authenticate to Azure AD.

Now that we have our guard, let create our routing (I’ve already added three components to the application called home, login and values):

Now we can add our routing module to our application. Open the app.module.ts file and import and add router to it:

We will need a login component which will handle the unauthorised requests:

Very straightforward, we just call login method on clicking a button. Of course you can do it on load without need to have a button, this will just makes debugging a bit easier.

At this point let’s add the Azure configuration to our app. First we need to define the same Azure configuration that we used for our ASP.NET Core application. So head to your environments.ts and add them:

The adal-angular4 requires the tenant Id and client id (which is the same as application id) and a post back URL. Remember that we’ve set the same when creating the application on Azure AD.

Alright, time to initialise this service. Open up your app.component.ts file and import the Adal4Service from this package, then call init method and pass the above config to it:

Because of that post back URL we’ve defined, we also need to handle the login callback coming from Azure AD. We do this by calling handleWindowCallback from the aforementioned service on init.

Let’s define the HTML for the app component as well:

It is very simple. We have a menu which is pointing to our routes, a login/logout button which is shown based on user current status, and the router outlet which will load the correspondent component.

Let’s create our services which are required to finish our application. First we will need a base service which can extract the token from user object and add it to request header as bearer token:

I am using a generic class which can be used later using TypeScript features (which I love). In the constructor we need an instance of HTTP service, the base URL and the Adal4Service to extract the token from.

Now let’s add our values service:

Now you know what was the benefit of having that generic class, it’s superb isn’t it?

Note: I am using an config object which can be injected anywhere. The source code for that is very simple:

Alright, time to consume the values service in the values component:

And the HTML:

Finishing touches

It is not time to glue everything together. Open your app.module.ts and add all the services you need (components will get added when you add them using ng g component command):

As you can see we’ve provided all the required service we added. Also configured the Adal4HTTPService which then will get used by Adal4Service and specified its dependencies.


Since we are using two different project we will need to let Angular CLI know when to delegate the requests to our ASP.NET Core APIs. For that you can simply create a proxy and use it when using ng serve:

The port defined above need to be the port that is used to lunch you API application. Also you will need to let ng know it should use a proxy. Open your package.json and replace ng serve with ng serve --proxy-config proxy.conf.json.

Now run dotnet run in root of API’s and run npm start from the root of the Web folder. And it is all done. When you click on values menu you will be redirected to your Azure AD where you can login and then you will be redirected back to your application and the values will be loaded.

Hope you will benefit from this post and remember to spread it (short link) where you see fit.

Again the complete source code can be found on my GitHub repository.


Spread the love

4 Replies to “Integrating your SPA with Azure AD13 min read

  1. Good explained. Do you know if it is possible to acquireToken also if the api are placed on Another machine?


    1. Definitely, with OAuth2.0 that would be your token provider, but you have to allow CORS and add that address to your HTTP headers as trusted


  2. Good sample, Do you have a sample with Angular 2 and core 2.0?


    1. The sample API’s are already written in ASP.Net 2.0, and you can just use the same client app code with angular 2, just initiate a new angular 2 app with the same name and copy the code. You should be good to go


Leave a Reply