Extending and Customizing authentication mechanism in Web Applications using ASP .NET Identity

Background

ASP.NET security module evolved time to time. First in 2005, Microsoft introduced ASP.Net Membership which is used to authenticate users using Forms authentication and the user names, password etc. stored in the SQL Server database. There were few limitations with this framework as the database schema was designed for SQL Server only and you cannot change it. Secondly, if you wanted to extend some more properties related to profile information etc. you have to create separate tables. Another limitation is OWIN. Since the authentication is based on Forms Authentication, the membership cannot use OWIN.

What is OWIN: OWIN includes middleware components for authentication that supports to log in users from external authentication namely Microsoft Accounts, Facebook, and Twitter etc. OWIN also includes support for OAuth 2.0, JWT and CORS.

Today, everyone maintains social network accounts like Twitter, Facebook, etc. and people most likely prefer to login or linking applications with these accounts rather creating new ones.

Keeping all these limitations Microsoft developed another framework “ASP.Net Identity” that does not only supports OWIN but more or less the extension and customizing of the authentication module is far easy and practical as compared to the ASP.Net Membership framework.

What is ASP.Net Identity?

ASP.Net Identity is a new membership framework to provide user logins and security in web applications. It allows adding login features in web application and also easily customizable to extend the user information.

Following are some of the feature of the ASP.NET Identity system taken from http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

One ASP.NET Identity system

  • ASP.NET Identity can be used with all of the ASP.NET frameworks such as ASP.NET MVC, Web Forms, Web Pages, Web API and SignalR

Ease of plugging in profile data about the user

  • When you create new users in your application, it is now easy to add extra information about the user. For eg.. if you wanted to add a Birthdate option for users when they Register an account in your application.
  • ASP.NET Identity uses Entity Framework Code First and it is possible to extend the POCO classes.

Persistence control

  • By default the ASP.NET Identity system will store all the user information in a database. ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.
  • If your application requirements are that this information might be stored in a different storage mechanism such as SharePoint, Azure Table Service, No Sql databases etc. it is now possible to plug in different storage providers.

Unit testability

  • ASP.NET Identity makes the web application more unit testable. You can write Unit Tests for the parts of your application that use ASP.NET Identity

Simple Role provider

  • There is a Simple Role provider which lets you restrict access to parts of your application by Roles. You can easily create Roles such as “Admin” and add Users to Roles.

Claims Based

  • ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims. There is a Claims

External Logins

  • You can easily add external logins such as Microsoft Account, Facebook, Twitter and Google to your application store the user specific data in your application using this system.
  • You can also add login functionality using Windows Azure Active Directory and store the user specific data in your application using this system.

ASP.Net Identity comes with ASP.Net MVC 5 or you can also add it using NuGet Package manager console. Identity framework is based upon three libraries namely

  • Microsoft.AspNet.Identity.EntityFramework

    This package has the Entity Framework implementation of ASP.NET Identity which will persist the ASP.NET Identity data and schema to SQL Server.

  • Microsoft.AspNet.Identity.Core

    This package has the core interfaces for ASP.NET Identity. This package can be used to write an implementation for ASP.NET Identity that targets different persistence stores such as Azure Table Storage, NoSQL databases etc.

  • Microsoft.AspNet.Identity.OWIN

    This package contains functionality that is used to plug in OWIN authentication with ASP.NET Identity in ASP.NET applications. This is used when you add log in functionality to your application and call into OWIN Cookie Authentication middleware to generate a cookie.

     

Steps to extend and configure ASP.NET Identity

Usually mid – large sized web applications are divided into different layers i.e. Presentation, Service, Business, Data Access etc. and usually models resides on the common layer which can be used by data access, service and presentation layers. When designing the architecture of web application and implementing security we have to follow the basic style of placing code in specific layers otherwise the code become shambolic.

In ASP.Net Identity, as the models are related to ASP.Net identity framework resides in Microsoft.AspNet.Identity.EntityFramework and with the help of Code First entity framework we can easily provide the association with other entities where needed.

Let’s proceed with some hands-on now

1. Open Visual Studio 2013 and create a new Web application project and select MVC template. If you create a web application project using Visual Studio 2013 you will automatically get these three assemblies referenced by default.

 2. In case if you have Visual Studio 2010 you can manually add it using NuGet Package manager console and search term ‘asp net identity’

 

 

3. Open AccountController, you will notice that its calling parameterized constructor from default AccountController constructor and initializing UserManager, UserStore and ApplicationDbContext


public class AccountController : Controller
{
public AccountController(): this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser> (new ApplicationDbContext()))){

  }
public AccountController(UserManager<ApplicationUser> userManager)

UserManager = userManager;

  }

 

4. UserManager is basically the entry point for performing signing operations, it takes UserStore as a parameter which is implemented by IUserLoginStore, IUserRoleStore, IUserClaimStore, IUserStore etc to provide repositories for user-related data such as user data, passwords, claims, roles etc. UserStore takes a DbContext as parameter and have the implementation details of how the particular User is stored. If you notice the ApplicationDbContext it is derived from IdentityDbContext and not the standard DbContext class this is because the IdentityDbContext is specific to the ASP .NET Identity framework and it allows entities to have String as a primary key.

5. Let’s generate a database from Identity framework entities using entity framework code first approach.

 a. In the visual studio, open Package Manager Console and select your web project as the startup project. In case if you have different layer for data access components you can select that specific layer and add the references to the ASP .NET Identity framework libraries via Nuget.

 b. Execute command enable-migration, that creates a Migration folder and create a Configuration class. Note: you can also enable the automatic migration by settings its AutomaticMigrationsEnabled property to true in the configuration class constructor.

 

c. Now open the ApplicationDBContext class and see which database connection name it’s pointing to. By default its pointing to DefaultConnection

 

 

d. To migrate the Identity tables into existing or separate database, we can change the connectionString as

 

<add name=DefaultConnection connectionString=Data Source=.\mssqlexpress;Initial Catalog=TestDB;Integrated Security=False;

User Id=sa; Password=sa123; Timeout=500000providerName=System.Data.SqlClient />

e. Now execute add-migration command in the package manager and name it Initial

 

f. It creates a class with two methods Up() and Down(), Up will be called to sync the changes from code first model to the database, and Down can be used to revert changes back to last state.

 

 

g. Now execute update-database command so the new database and identity tables will be created.

 

 

 

6. We can also create custom tables by adding DbSet properties for new tables in the ApplicationDbContext class and customize it according to our need.

7.  Let suppose, we want to extend the security module and provide page level security in which whenever the user navigates to any page system checks the feature set of user that belongs to particular role and redirect it to the login page if it does not exist. To handle this scenario we can follows below steps

a. Create a model named as View

public class View{

public String ViewName { set; get; }
public String ViewQualifiedName { set; get; }
public Int64 ViewParentId { set; get; }

}

b. Create another model named RolePermission

public class RolePermission{
public IdentityRole RoleId { set; get; }

 public View ViewId { set; get; }

          }

c. Add the DbSet property for RolePermission and View in the ApplicationDbContext class

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{
public ApplicationDbContext() : base(“SecurityTestDB”, throwIfV1Schema: false){
}
public DbSet<View> View { set; get; }

  public DbSet<RolePermission> RolePermissions { set; get; }

   public static ApplicationDbContext Create(){
    return new ApplicationDbContext();

  }
}

d. Follow the same steps as above to migrate model changes into database.

e. When we run the migration using add-migration and update-database commands it will create another table named as View in the SecurityTestDB and defines one to many relationship between ASPNetRoles and RolePermission table and View and RolePermission table.

8. Now let suppose we need to add more fields in the AspNetUsers or any other identities table we can customize it by adding a new class inheriting from Identity* class and specify new properties.

a. For example in the ASPNetRoles I need to add IsActive bit which can be used to enable/disable role rather deleting it completely I can create new class named SecurityRoles

b. Derive SecurityRoles with IdentityRole

c. Add IsActive Boolean property as follows

d. Enable migration

 public override void Up(){
AddColumn(“dbo.AspNetRoles”, “IsActive”, c => c.Boolean());

 }

 public override void Down()
{
DropColumn(“dbo.AspNetRoles”, “IsActive”);

}

 


 

 

 

With the power of Entity Framework and new Identity framework its quite easy now to customize security framework according to our need. The beauty is that the core classes remain intact and it doesn’t harm the underlying logic of the authentication mechanism provided by Microsoft.

 

Advertisements

One thought on “Extending and Customizing authentication mechanism in Web Applications using ASP .NET Identity

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s