Understanding Asp DotNet Identity Part II



In the previous post we laid out all the ground work needed to integrate the Asp .Net Identity in your new Empty MVC application. In this post we will continue further and implement the registration page.

Add Account Controller & RegisterViewModel Class

Asp .Net Identity

RegisterViewModel is a simple ViewModel class that we will use to collect the user information from the registration screen to pass it back to the controller.

Asp .Net Identity

I have also configured Bootstrap and its dependency library in the project using Nuget Package Manager.

Asp .Net Identity

Using bootstrap I have also configured Layout (Master Page) along with the default ViewStart page.

Asp .Net Identity

Create Register View using scaffolding

Right click on the Register action method and select "Add View".Select following options when the dialog opens.

Asp .Net Identity

I have modified the generated HTML slightly to use the CSS classes coming from Bootstrap. With this changes go ahead and run the application and navigate to the Account/Register URL. Make sure the project compiles fine and you are able to navigate to the Registration view.

Asp .Net Identity

Okey, with the page running ok let's get back to the Post action of the Register method to see how to actually create the user account. The controller will need access to ApplicationUserManager and AuthenticationManager instances which we are going to obtain from HttpContext unless it is passed from some dependency injection framework.

Asp .Net Identity

And following is how our Register POST action looks.

Asp .Net Identity

Register User Account

Now that everything is setup and in place, let's go ahead and register an account. Try passing the password that is not matching validation rules and you will see error as below.

Asp .Net Identity

Once you provide proper Username and password you might get an error while navigating to Home/Index. That is because we have not yet defined the HomeController or Index View. Let's examine the database. And as expected you will see much cleaner table schema for new Identity framework.

Asp .Net Identity

Let's also make sure that our new user has been created in the database.

Asp .Net Identity

Let's also quickly implement the LogOff ActionMethod on our account controller as shown below.

Asp .Net Identity

At this point, we have the basic account creation working with Asp .Net Identity framework. On the surface it might look like a lot of work as compared to Asp .Net Membership provider but this is a more robust way of doing things these days. Specially when the security is moving towards Claim based model. Also remember that some of the work we did earlier was related to OWIN based hosting of the application.

in the coming posts we will see how we can extend the same sample with some more advanced middleware components like Email confirmation, Two-Factor authentication etc. Happy coding.