How to call an ASP.NET Web API secured by Azure AD from an AngularJS Single Page App

How to call an ASP.NET Web API secured by Azure AD from an AngularJS Single Page App

Data breaches, they are an unfortunate and sadly too common occurrence these days. Seems like not a few weeks or days go by before we hear of yet another data breach. Take for instance this article outlining some of the companies that lost your data in 2015: http://www.zdnet.com/pictures/biggest-hacks-security-data-breaches-2015/

With such a high probability of data compromise the need for a higher level of security is quickly arising, and when it comes to even basic authentication being added to a web application, such task can no longer occupy the backseat, but rather it needs to be at the front center. So if you are a developer that needs to ship your application on time but wants to make sure things are secure and trustworthy, what can you do? Thankfully, I believe there is a good solution these days that provides a high level of security and it opens up future extension points that can maximize your development investment and perhaps even give the application a higher competitive advantage. I am referring to Azure AD.

The following sample application has been forked by yours truly from a sample application provided by Microsoft, you can find the original example application at: https://github.com/Azure-Samples/active-directory-angularjs-singlepageappdotnet-webapi . However, I wanted to do something a bit different than the sample application was doing. There seems to be a couple of examples contained within the application, one that relies on some server side configuration that I felt was not needed for a SPA example. In fact, it was a bit confusing for me at first when I looked at the example and tried to figure out why I was configuring a web.config file alongside the JavaScript configuration as noted in the GitHub instructions for the example SPA application. Thus, I decide to fork it and hopefully tried to simplify the concept a bit more to my liking. While at the end of the day doing so might just be a matter of configuration preference, it is also more fun to do something different and see what we can get, don’t you think?

Without further ado, let’s dive in.

We’ll first proceed to configure the application. The first thing to do is to head over to Azure AD and create a new Azure Directory, if you already have one and you would like to use it then that will work fine. The following steps are similar to the ones shown on the GitHub documentation for this particular Microsoft example, I am simply expanding on them a bit. I am also going to assume that you have not done this before, so I will strive to provide as much detail in each step as I can.

Create a new Azure Active Directory

So first things first, create a new test directory in Azure. Just click on the ‘New + ‘ button at the bottom of the Classic Azure Portal and follow the prompts:

In my case I already have a directory called ‘sampleapps’, so the name is not available, but you should be able to create your own and when ready press the forward arrow and just like that, you have a new Azure Active Directory:

Here is my new test directory:

Now that we have decided on our Azure Sample AD (Active Directory), we are now going to create the application settings. On the Azure AD page you will see an Applications tab, click on that tab. Notice that if you have an Office 365 Subscription, you will already see that entry as an App on this page. That is because Office 365 leverages Azure AD, but that is a topic for another time.

Registering the Web API with your Azure Active Directory tenant

Within your selected Azure Active Directory, click on the Applications tab, you will see and ADD icon at the bottom of the page, click on that and you will see a dialog asking you what you want to do:

Click on Add an application my organization is developing and you will see the **ADD APPLICATION **screen next:

Give your application a name, select WEB APPLICATION AND/OR WEB API for your SPA sample application, and click the forward arrow at the bottom right:

On this next step we need to give the Azure AD configuration for our application the URL from where we will be signing from, in this case the URL is where we are running the project from https://localhost:44327/:

The next piece of configuration on this next screen is the App ID URI. This is simply your tenant name followed by your application name in this format:  <a href="https://<your_tenant_name>/ToGoAPI">https://<your_tenant_name>/ToGoAPI</a>. Simply replace <your_tenant_name> with the Azure AD tenant name you created earlier. Once you have filled the information, save it and move to the next stage.

If everything is successful you will see something similar to this:

Registering  the SPA with your Azure Active Directory tenant

The previous steps walked you through the process of registering the TodoAPI, now you will need to follow the same process to register the TodoSPA application in Azure AD. So head back to the Azure management portal, make sure you are again within the Directory where the sample application configuration lives.

Once you are in the Directory where you are planning to register the TodoSPA, click on the Applications tab and then click on the ADD button at the bottom and on the next screen select Add an application my organization is developing. Enter a friendly name for the application and click the forward arrow:

Next you will enter the details for the SIGN-ON URL and the **APP ID URI. **In this case the URL you will be signing in from is the one where the TodoSPA is hosted:

Now you will have to setup the permissions for the TodoSPA application to access the TodoAPI within the configuration tab of the TodoSPA application in the Azure AD’s administration portal:

Scroll down to the section where you can see permissions to other applications:

Click on the Add application button, you will see a new screen pop up title Permissions to other applications, here you will add the To Go API application permissions. Now, this particular UI is less than intuitive in my opinion, so I will briefly walk you on how to add the ‘To Go API”.

This is the screen that you first see after you click on Add application:

Under the SHOW dropdown list, click on it and select All Apps from the options:

Next you will type in ‘to go api’ in the STARTING WITH  search field input, and then click on the checkmark button on the far right:

You will now see the ‘To Go API” listed under the results section, make sure you click on that row to select it, once you do so a green checkmark will display next to the name:

In order to save your changes, click on the bottom right arrow:

You should now see the “To Go API” on the list of permissions to other applications:

Then click on the Delegated Permissions: 0 for the “To Go API” row and check the permission:

Make sure you save your changes and wait for the page to finish persisting the changes

Configure the Web API with your Azure Active Directory tenant

On the Azure Portal, navigate to the ToDo SPA configuration tab and copy the client id from that page:

Now head over to the Visual Studio 2015 solution, and open the web.config file under the ToGoAPI project

Now, this is where I also ran into some issues while following the Microsoft instructions on GitHub. The instructions on GitHub state that the ida:Audience value should be the App ID URI, e.g. https://your_tenant_name/ToGoAPI. But when I tried running the application I continued getting an error that I was not authorized to access the API, even after I had authenticated with Azure AD. So I changed the value to use the actual hash for the audience key, which in this case it the client id of the SPA application. I am not sure yet why the initial configuration did not work for me, but while I research on that you can just use the client id for your sample and make it work like that if you need to. Therefore, you will be replacing the values for ida:Tenant and**  ida:Audience** with the values from your Azure AD configuration:

Since you will be calling the Web API from a different URL than the one the Web API is hosted on, you will have to enable support for CORS in the Web API. If you have not encountered CORS before and  would like to know more about it, just head over to this MSDN article  that explains it in detail: https://msdn.microsoft.com/en-us/magazine/dn532203.aspx . I have found that the simplest way to enable CORS for this sample is to simply add it on the Startup.Auth.cs file. This file will also contain a reference to the two application settings keys we just added:

In a real world application you may not want to use the setting for CorsOptions.AllowAll, but this will suffice for this example.

Now head over to the TodoSPA project and locate the App/Scripts/app.js and locate the endpoints object declaration:

and update the key value pairs with the respective root location and App ID URI for the application, in this case it is something like this:

One more thing we need to do on the TodoSPA project is to head over to the App/Scripts/toGoListSvc.js and update the URL from where you will be getting the data to consume by the front end application. In that file you will simply update the URL for your local Web API endpoint https://localhost:44327/

Enable the OAuth2 implicit grant flow

There is one more configuration step that needs to be done in Azure AD in order to make all of this work. You will need to enable the OAuth2 implicit grant by downloading a manifest file and editing some JSON.

On the page for the “To Do SPA” application configuration, you should see a MANAGE MANIFEST  button icon at the bottom of that page:

Click on the** MANAGE MANIFEST** and select Download Manifest

Click on the next Download manifest link and save the file to your local drive:

Open up the file in your favorite editor, in my case Visual Studio Code, and locate the ‘oauth2AllowImplicitFlow” setting. The default value is false, so we will go ahead and set it to ‘true’ and save the changes to the file:

Head back to the Azure AD management portal for the “To Go SPA” application configuration, click on the MANAGE MANIFEST button and this time choose Upload Manifest and select the new file you just saved:

The last configuration step is to update some settings on the Todo SPA code project.

Configuring the SPA to use your Azure Active Directory tenant

Here we will need to update the configuration for ADAL JS. This is a library that provides all that you need to authenticate against Azure AD from within a JavaScript application.

In the TodoSPA code project, locate the App/Scripts/app.js file and then find the section where the **adalAuthenticationServiceProvider.init **function is called and update the ‘tenant’ and ‘clientId’ with the values from your Azure AD configuration:

And that is all you will need as far as configuration is concerned for this example.

Running the application locally

Now you are ready to run the application, but before you do make sure that in your solution settings you have both, the SPA and Web API projects, set to start at the same time:

Next, just press F5 on Visual Studio 2015 and you should see your browser launch two tabs, one for the SPA and one for the Web API. Notice the ‘Login’ button on the top right corner of the  SPA, click on that and you will be redirected to the Microsoft login page:

Noticed that the ‘Login’ changed to ‘Logout’ once you go through the sign-in process and become an authenticated user of the application.

Lastly, you now should be able to click on the ‘To  Go List’ tab and conduct simple CRUD operations:

The Todo SPA application communicates with the Todo Web API application securely via Azure AD. The Web API trusts Azure AD to have authenticated the caller, in this case the SPA, using the user’s credentials. Adding a breakpoint on the Web API controller, we can see that the user is indeed authenticated:

And that is all!

Retrospective

You might feel that this is quite a bit of configuration for securing applications, and I wouldn’t blame you. However, security as you already know is hard, and even though these steps may seem like a lot at first, they are also necessary to keep things locked down.

However, there are more changes coming from Microsoft in the shape of more unified libraries that continue to embrace open security protocols while minimizing the tax a developer must pay to implement secure applications. The following Build 2016 talk is from Vittorio Bertocci and I highly recommend watching it for getting a broader perspective on where things are at and where they are going with Microsoft Identity: https://channel9.msdn.com/Events/Build/2016/B868

In the words of Mr. Bertocci, Microsoft’s plan for Azure AD is to create “…the BEST identity system for ALL developers.” And I would agree that so far the journey has been quite fun, and I look forward to diving in more deeply into the realm of Azure AD and security in general.

I hope you enjoy the blog post. I will be posting the updated link to my fork of the source code example soon…

Until next time.

Update: Here is the link to the sample source code: https://github.com/jpvelasco/active-directory-angularjs-singlepageapp-dotnet-webapi