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.

 

Implementing Validation mechanism in ASP.Net MVC project using Unobtrusive JavaScript for validation

In this article I will walk you through the steps of implementing validation in the ASP.Net MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example

<input
type=”button”
id=”btn”
onclick=”alert(‘hello world’)
/>

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {

$(‘#btn’).click(function (e) {

    alert(‘hello world’);

}

});

For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. In ASP.Net MVC, you know that there are many HTML helper functions like @Html.TextBoxFor, @Html.EditorFor, etc. that takes an expression and attributes. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example

If our model is


public
class
Person : Message

{

[GridColumn(“Id”, true)]


public
int Id { set; get; }

 

[Required]

[GridColumn(“Name”, false)]

[StringLength(10, ErrorMessage=“Length cannot exceed to 10 character”)]


public
string Name { set; get; }

}

In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this


@Html.EditorFor(model => model.Name)

This will generates an html as follows


<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

You can see that depending on the model it has automatically added the data-val-* properties in the html.

There is no magic, actually in order to make this work

  1. You have to add a jquery.validation.unobtrusive.js in your project.
  2. Then add the file path in the bundle like this

     

    bundles.Add(new
    ScriptBundle(“~/bundles/jqueryval”).Include(


    “~/Scripts/jquery.validate*”));

     

  3. Then add the script reference in the page as within the script section like this

@section scripts{


@Scripts.Render(“~/bundles/jqueryval”)

}

       4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this

$(‘#Save’).click(function (e) {


var $val = $(this).parents(‘form’);


if (!($val.valid()))


return
false;


else alert(‘form have no errors’);

}

Hope this helps!