Skip to main content

Android and iOS Mobile Application Development (Part 2): Securing our Web API application with Azure Active Directory OAuth

Welcome to the second part of the series on Android and iOS Mobile Application Development. Before we begin learning about how to setup Azure Active Directory for securing our Web API, let's first take a deep dive into why we have chosen Azure Active Directory and OAuth to secure our Web API.

Why not use ASP.NET Forms Authentication Cookie?

Securing our web application traditionally, typically involves validating a user's username and password against our database store, and creating our own ASP.NET forms authentication cookie if the credentials matches. With newer versions of ASP.NET, an identity database can be easily created and utilized with ASP.NET forms authentication cookie issued via the identity framework. This means we spend even less time writing our own custom database store and writing validation code.

However, there are still some drawbacks with ASP.NET forms authentication cookie. The security disadvantage can be best explained by Microsoft here, which talks about the web API application being vulnerable to cross-site request forgery (CSRF) attacks.

In addition to security, when your web application is running in a web browser, the web browser will automatically handle the caching of the forms authentication cookie and adding of the authentication cookie for you on each outgoing request. In contrast, in the context of a mobile application, we will have to handle it ourselves. This complicates the implementation details. We will explain more about how OAuth can help us in this respect in a little bit, but first, let's talk about Azure Active Directory.

Why use Azure Active Directory?

The reason why we chose Azure Active Directory is that we want to push ourselves out of the authentication business and be focused on our actual business. We don't have to worry about managing users credentials anymore and have a database to manage that. We don't have to worry about implementing policies for password expiration, or recovery. We can be ensured of a high level of availability. Eventually, what this broils down to, is that our resources are now spent more on implementing the business requirements rather than infrastructure services.

Note that we are talking about authentication here. We still have control over what a user can do because we can still build around the authorization concept. Once we know who the user is after login, we can write code to control what they have access to. This itself can be a different topic.

The OAuth dance - Authorization Code Grant Flow

As a note, with Azure Active Directory OAuth, we are really talking about OAuth 2.0. More information about the specifics can be found here. There are many use cases that OAuth supports, but for our purpose, we are using the Authorization Code Grant Flow.

  1. Before a user is able to access a secure resource (via Web API call), the user is first going to be redirected to the sign-in page.
  2. Once login is successfully, it will redirect back to our application will with a code.
  3. This code will allow us to invoke an OAuth call to exchange for an authorization token. The authorization token contains a code which we can use, has an expiration timestamp, and also carries a refresh token.
  4. We can use of the code from the authorization token to make actual calls to our Web API. Web API will now be able to recognize the identity of the user who made the call and give access to the secure resource.
  5. Once the authorization token has expired (by checking the expiration timestamp), we can make use of the refresh token to get another authorization token.

Azure Active Directory Setup

As of the writing of this article, it appears that Microsoft Azure has a new website at portal.azure.com, but the Azure Active Directory link still appears to be redirecting back to the old website at manage.windowsazure.com. The user interface may have changed but I believe the idea should still be consistent. When we are in the Azure Active Directory page, we should be able to create a Azure Active Directory for our Mobile Application.

Let's find Active Directory on the left side navigation and click on the + New button.

Let's select Directory and Custom Create.

We will need to provide a name for our Active Directory which can be anything you wish. The domain name will always end with .onmicrosoft.com and can be whatever you wish. Obviously, the country or region should be as close to where your users are located. Bear in mind that the name and domain name are not updatable. As a suggestion, try not to make the name of the Active Directory specific to your Mobile Application if you intend to create other related Mobile Applications.

Creating Azure Active Directory Application

Once your Azure Active Directory has been created. we can go ahead and create our applications. Now, we may think we just create a single application for our Web API. However, this is not complete. We will actually have to create two applications. One application is definitely for our Web API, however, the second application is for our Native Mobile Application. Yes, we do need to create it so an application Id can be assigned to it as part of the information sent for our OAuth dance.

Adding our Web API application

Let's click on Applications and click on the ADD icon on the bottom center.

Select: Add an application my organization is developing

Give a name for your Web API application, Choose Web Application/And Or Web API and click on the next button.

The Sign On URL is there if you are creating a Web Application and that's where the user will be authorized to be redirected to after they sign in. Think of this as your landing page. The application Id URI is really an identifier for your application but needs to be in the form of a URI. It does not have to be valid.

Once our application has been created successfully, we can click on Configure on the top bar to take a look at the application details.

If you review the details of your new application, you will notice the following: USER ASSIGNMENT REQUIRED TO ACCESS APP. I would strongly suggest turning on this option so user access is explicit, based on an actual assignment.

Now, we are ready to create our mobile application.

Adding Mobile application

Let's click on Applications and click on the ADD icon on the bottom center.

Select: Add an application my organization is developing

Give a name for your Web API application, Choose Native Client Application and click on the next button.

The Redirect URI is really to redirect the user back to your Mobile Application. However, we know that a Mobile Application does not have a URI. It is actually running in the context of your Mobile Device Platform. So, what I did was to host a simple callback .HTML and have my redirect URI be there. The .HTML page does not actually do anything. It is just there so we can have a place to redirect to.

Now, we are ready to start adding some users to our web application.

Adding user to your Application

From our Active Directory, let's select users.

Let's click on the ADD USER icon on the bottom center.

There are a few types of users we can create. If our user already has a public email profile, we can easily add them with their public email profile using the User with an existing Microsoft account option. If this is a non-Microsoft email profile, Microsoft will allow these users to setup a Microsoft account and send them a verification email to their public email profile. Once verified, the user is setup.

Another type of user is our Active Directory user. The email domain of this user always ends with [username]@[Your active directory].onmicrosoft.com. This is a great way for you to create demo users or test accounts if you desire.

The process of creating these 2 types of users should be pretty straight forward, so go ahead and create a user of your choice.

Assigning user to your Application

If you had not enabled the option: USER ASSIGNMENT REQUIRED TO ACCESS APP stated previously, you can skip this step. However, if you did, you can choose your Application and select the Users options.

Here, you can assign user access to your application and clicking on Assign button. The same steps goes for unassignment, where you would choose Remove. Very simple!

If you are wondering, we do not need to repeat this for your Mobile Application. Next up, we will talk about how to secure your Web API application.

Setting up your Web API application

Startup.Auth.cs (located in App_Start) and setup the following within ConfigureAuth

   
using System.Configuration;
using System.IdentityModel.Tokens;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;

namespace Demo1.Web
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
              new WindowsAzureActiveDirectoryBearerAuthenticationOptions
              {
                 Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                 TokenValidationParameters = new TokenValidationParameters
                 {
                   ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                 },
              });
        }
    }
}

Open your web.config and update the Tenant and Audience app settings. These settings comes from the application details page.

The Client Id should be set in ida:Audience. The App Uri Id without the http:// prefix with a .onmicrosoft.com suffix should be set in the ida:Tenant.

  
<add key="ida:Tenant" value="[YOUR_APPLICATION_NAME].onmicrosoft.com" /> 
<add key="ida:Audience" value="[YOUR_APPLICATION_ID_GUID]" />

Finally, simply apply the [Authorize] attribute on your base Web API (or simply on your Web API) Controller. That's it. Your Web API is now secured by Azure Active Directory OAuth.

 [Authorize]
 public class BaseApiController : ApiController
 { ...

I hope you have enjoyed the second part of the series on Android and iOS Mobile Application Development. In the next article, we will look at how we can write our mobile application using Apache Cordova. We will be making use of the setup we have done today to implement authentication via Azure Active Directory. Stay tuned for part 3!

Comments

Post a Comment