Web Resources Access Protection Using ASP.NET Identity

In the era of mobility and interconnected smart devices there are cases when the access to information should be restricted for non-authenticated entities.

The aim of this article is to provide high-level details about ways of authentication and authorization for software developers that are using ASP.NET platform, especially ASP.NET MVC. In the following lines I will talk about the ASP.NET Identity infrastructure. I will walk you through the main features of the framework, and show you how this system may be customized in order to serve different scenarios.

What is ASP.NET Identity?

In order to answer this question, as authors of [1] explain, one may say that the idea behind this framework would be a solution that will provide:

  • a unique authentication and authorization mechanism with persistence control, easy to extend and unit test, also providing OWIN middleware, in order to be used for any specific application(web, mobile, cloud);
  • role and claim based authorization;
  • plugin-able infrastructure for different log in providers, such as Microsoft, Google, Facebook, Twitter, etc;
  • facilitates Azure Active Directory

Architecture Overview

Out of the box the ASP.NET Identity framework provides a working membership solution. From a high-level point of view, the architecture of the framework is based on the following aspects: managers, who are responsible for the information processing/handling, and stores, which represent the implementation of the data persistence. These two concepts are decoupled, offering developers the opportunity to plug-in various storage providers.

By default, the persistence mechanism is implemented based on the Entity Framework Code First concept. In order to store data, a set of tables should be generated:

  • a table that will store the registered user information – user id, user name, maybe a hashed password;
  • another one representing roles – may be interpreted as authorization groups;
  • claims table – set of information that may identify a user;
  • logins table – representing data from external authentication providers such as Microsoft, Facebook, Google, Twitter, etc;

The main parts of the framework consist of:

  • AspNet.Identity.Core – users, stores and managers logic;
  • AspNet.Identity.EntityFramework – EF persistence specific implementation;
  • AspNet.Identity.OwinOWIN middleware specific business logic for the identity framework.

The following diagram illustrates the architectural components of the framework:

 

Figure 1. ASP.NET Identity Components

 

Taking into consideration the core part of the framework, the following diagram presents the abstractions of the user and store concepts:

 

Figure 2. ASP.NET Identity Core Abstractions
There are a set of stores derived from IUserStore:Observing the core structure, we may observe that the base entities are the IUser and IRole, which are utilized in stores, IUserStore – user management, respectively IRoleStore – role management.

  • IUserClaimStore – stores user specific claims;
  • IUserEmailStore – stores email;
  • IUserLockoutStore – access failures and lockout status;
  • IUserLoginStore – maps users to login providers: Google, Facebook, Twitter, Microsoft;
  • IUserPasswordStore – stores the password hash for a user;
  • IUserPhoneNumberStore – stores phone number;
  • IUserRoleStore – maps users to their roles;
  • IUserSecurityStampStore – stores security stamp;
  • IQueryableUserStore – exposes IQueryable users.

On top of the stores we have the managers. They are responsible for the orchestration of the changes, respectively:

  • UserManager – exposes functionality that will save changes to user store,
  • RoleManager – provides logic for saving the changes related to the role store.

In case the Entity Framework does not suit for your project, there are some custom storage providers already written, that support:

  • MySQL;
  • Azure Table Storage;
  • ElasticSearch;
  • CouchDB / Cloudant;
  • MongoDB;
  • NHibernate;
  • RavenDB;
  • Redis.

If these providers are just not the ones that you need, there is the possibility to write your own. In order to do that, you have to take into consideration, at least, the following:

  • data source to be used,
  • data that have to be stored: user information, user claims, user logins and roles;
  • store classes: user store, user claim store, user logins store, user role store;
  • data access layer that will operate with store classes.

External Authentication

There are some scenarios when the application that is being developed needs to offer the possibility of authentication by another source, not only the traditional membership where the user information is maintained into a local database. In this case, the developers may use the built-in support for external provider implementation.

There are two standards for authentication that allow users to utilize their accounts from trusted providers. These are OAuth and OpenId. By some experts, the OAuth protocol was built mainly for authorization, but there are a lot of cases when it is used for authentication. The good thing about these standards is that a lot of the providers offer implementation for them, saving the users from the registration process for different applications.

When using external providers first of all we have to ensure that the Authentication of the project is set to Individual User Accounts. Connecting to authentication providers like Google, Microsoft, Facebook, etc it is very important to set-up the connection to SSL, and it is a very good practice to keep using https after the login, in order not to transfer sensitive data in clear-text. When developing applications using ASP.NET MVC, the RequireHttps attribute can be used for enforcing all requests to use https and the Authorize attribute in order to specify the access restriction. Another approach will be to create a filter that will enforce all the requests to be over https. Configuring RequireHttps and Authorize for the entire application is considered as a security best practice.

Enabling sites to use external login when developing applications using ASP.NET MVC 5 is done through App_Start\Startup.Auth.cs where the authorization providers are configured. Depending on the protocol implemented, OAuth or OpenID, the provider will request a registration process or not, in order to provide   authentication data. Due to the fact that ASP.NET Identity has built OWIN middleware the configuration of external provider is very easy to do regardless the protocol implemented by the provider.

The following listing presents the  App_Start\Startup.Auth.cs with the OWIN configuration in place:

public partial class Startup

    {

// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864

public void ConfigureAuth(IAppBuilder app)

        {

// Configure the db context and user manager to use a single instance per request

app.CreatePerOwinContext(ApplicationDbContext.Create);

    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

// Enable the application to use a cookie to store information for the signed in user

app.UseCookieAuthentication(new CookieAuthenticationOptions

            {

                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

                LoginPath = new PathString(“/Account/Login”),

                Provider = new CookieAuthenticationProvider

       {

OnValidateIdentity =

SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(

                validateInterval: TimeSpan.FromMinutes(5),

                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

       }

            });

// Use a cookie to temporarily store information about a user logging in with a third party login provider

  app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

// Uncomment the following lines to enable logging in with third party login providers

//app.UseMicrosoftAccountAuthentication(

//    clientId: “”,

//    clientSecret: “”);

//app.UseTwitterAuthentication(

//   consumerKey: “”,

//   consumerSecret: “”);

//app.UseFacebookAuthentication(

//   appId: “”,

//   appSecret: “”);

//app.UseGoogleAuthentication();

      }

    }

Listing 1. Startup.Auth.cs Class

After the registration process with the authentication provider is done, the next step will be to use the Startup.Auth.cs and to configure the application to use that provider. Note that storing sensitive data in code or config files is a security issue and this approach must be avoided. How to secure web applications for different threats and attacks is not the subject of the present article.

Conclusion

The main goal of this article was to present how ASP.NET Identity framework features may be used in order to control access to certain areas of your application.

In the first part of the article I talked about the general features of the framework, followed by some specific details on how the ASP.NET Identity framework can aid developers who need to add membership functionality to their applications. The second part of the article offers information about the framework’s architecture giving additional details about its abstract components, and also, providing information about what custom storage providers are already written and what aspects should be considered when there is a need to write a custom one. The final part, contains information related about the plug-in and configuration of an external authentication provider.

Considering the main features and the possibilities of extending and customizing the framework, the ASP.NET Identity should be considered when the development of an application using .NET technologies implies adding membership functionality.

This article was published in Today Software Magazine #42.

Useful Links

http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity
https://msdn.microsoft.com/en-us/magazine/dn605872.aspx
http://www.asp.net/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity
http://odetocode.com/blogs/scott/archive/2013/11/25/asp-net-core-identity.aspx
http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
http://www.asp.net/identity/overview/getting-started/aspnet-identity-recommended-resources