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!    

Sync Calendar Events using CALDAV in C#

In this post I will walk you through the steps of reading calendar events from CALDAV supported servers. Yahoo, Google, etc. supports CALDAV

What is CALDAV?

CALDAV is an internet standard allowing client to access scheduling information on remote server. It’s an extension of WebDAV which is a HTTP-based protocol for data manipulation. The protocol is defined by RFC 4791. As it’s an extension to WEBDAV protocol it uses HTTP verbs to manipulate calendar events some of them mostly used are PROPFIND, SEARCH, etc.

Background Information

  1. Every server has a separate URI to access calendar events.

Yahoo: https://caldav.calendar.yahoo.com/dav/user_name/Calendar/calendar_name/

Google: https://www.google.com/calendar/dav/user_name/events/

  1. Each Calendar folder is a collection and contains many calendar events. Each calendar event is a file and ended with .ics extension. .ics is well understood by many clients and you can easily export data from .ics to local client application.

How to Program

Now let’s see how to write a code to call Yahoo calendar events

  1. First of all create a new project in Microsoft Visual C# .NET
  2. Add reference to DDay.iCal library from Nuget Package manager console. This library will be used to read .ics files and read information about each event.
  3. Write below code to retrieve calendar event on any click event.

     


    In the above code snippet you have to configure your user name, password and modify the calendar URI depending on your calendarname and username.

If you see the code, I specified a content string which contains the request that I am sending it to the server. CALDAV have specific request formats which you can study here

ExecuteMethod is a helper method that sends request to the server and returns the response stream. Once I get the response stream I load the XML document and read the InnerXml of the file to get the complete XML. Then I parse the xml document and search for DAV:href element that contains the calendar event file (.ics) information. Once I get the list of .ics file paths, I call DownloadICS helper method to get the complete event information.

Helper Methods
Following are the helper method that performs specific operations. Please write these in your code to compile the project.

DownloadICS – Downloads .ics files


 

ExecuteMethod: Request calendar and returns response stream


Packt 2000th book Campaign

In the past, I have done few book reviews offered by Packt publishing and found that they have good set of technology related books.

Recently, they have launched an offer in which Packt is giving all its customers a chance to enjoy their books by giving them a free e-book copy for every purchase. This offer is valid from 18th March till 26th March 2014. People who are fond of reading technology related books must check here

 

Certificate error when deploying WCF Azure Service

February 25, 2014 Leave a comment

Last night I was working on some Azure WCF Service and while deploying on the Windows Azure Platform, I continuously faced error that “The certificate with thumbprint was not found in windows azure”. It was a simple WCF service based on BasicHttpBinding and has few operation contracts.

After doing deep research I found that while packaging a service from Package Windows Azure Application window, if you select “Enable Remote Desktop for all roles” or “Enable Remote Debugger for all roles” it expect to have certificates uploaded on azure portal and you should have specified the exact thumbprint in the Certificates section from properties window. Otherwise your deployment does not succeed.

Therefore, I succeeded disabling these two checks while creating a package and also made sure that there were no <certificates></certificates> tags inside service definition (.csdef) file and service configuration (.cscfg) file.

Hope this helps!

Reviewed Book “ASP.NET Web API: Build RESTful web applications and services on the .NET framework” by JoyDip Kanjilal

February 13, 2014 Leave a comment

I have gotten this opportunity to review the book named ‘ASP.NET Web API: Build RESTful web applications and services on the .NET framework‘ from Packt (UK based publishing company specializing in focused IT books).

Following is a review I made for this book

This book is very good to study the concepts of RESTful applications, SOA and ROA. Joydip have used different Microsoft technologies to showcase these terms. However, I found less information related to Web API which is the title of book and few topics like formatters, bindings and self-hosting web APIs are missing. I think there should be some chapter detailing the basic and advanced features of Web API that helps the reader to gain complete information on Web API.

Link to book page: http://www.packtpub.com/aspnet-web-api-build-restful-web-applications-services-on-the-dotnet-framework/book?utm_source=Book&utm_medium=mention.com&utm_campaign=Book_mention

Adding Queryable Support to ASP.NET Web API Controller Action Methods

January 18, 2014 Leave a comment

In this article I will show that how we can make our Web API methods queryable so the user can apply query operators and expressions to filter data.

We will use OData library for ASP.NET Web API that have the [Queryable] attribute provided, which facilitates in issuing queries.

1. Create ASP.Net Web API Project

2. Add sample model class which defines properties

3. In this example, I have created a Session class as follows

4. Now add a SessionController which will contain Get, Post, Put, Delete methods for CRUD operations.

5. It will create an empty controller. Now we will specify Get method and return session list as queryable.

6. Now add OData reference from Nuget Package Manager by searching as web api odata and click Install on Microsoft ASP.NET Web API 2 OData

7. Once you install, It will ask you to accept the license agreement, click I Accept and proceed

8. Now add [Queryable] attribute on GetSession method.

That’s it, build the solution and test.

9. Open fiddler and select GET HTTP Method and navigate to the URL i.e. http://[youraddress:port]/api/Session

10. Once you hit the above URI it will show you the complete session list in JSON format as follows

11. Now you can apply query operators on your request and filter data

Following are some query operators you can use to issue queries

$top=n: Returns only the first n entities in an entity set (or in Atom terms, the first n entries in a feed).

$skip=n: Skips the first n entities in an entity set. Using this option lets a client retrieve a series of distinct pages on subsequent requests.

$format: Determines whether data should be returned in JSON or the XML-based Atom/AtomPub format. (The default is Atom/AtomPub.)

$orderby=: Orders results, in ascending or descending order, by the value of one or more properties in those results.

$filter=: Returns only entities that match the specified expression.

$select=: Returns only the specified properties in an entity.

$inlinecount: Returns the server computed count of the number of entries produced by the query request.

Example

To select top 2, my URI would be like http://[youraddress:portNo[/api/Session?$top=2

Result:

Follow

Get every new post delivered to your Inbox.

Join 52 other followers

%d bloggers like this: