Adding ASP.NET Identity and Authorisation control to your MVC website

authorisationWhen you are building a website you will sooner or later want to build in some kind of Identification and Authorisation control to make sure not everyone can change your website or see sensitive information. In this tutorial I will show you how to build in simple Identification and Authorisation in your ASP.NET MVC website.

 

In this tutorial we start with an empty mvc project. You could also choose to start with an non empty ASP.NET MVC Application when creating a new project but I want to show you which files and references are required for ASP.NET Identity and this non empty project contains much more then only Identification and Authorisation.

Add required references

First lets start with adding all required references. Open the Nuget Package Manager and add all assemblies shown below:

Required assemblies

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.AspNet.Identity.Core
  • Microsoft.AspNet.Identity.OWIN
  • Microsoft.AspNet.Identity.EntityFramework
Nuget Package Manager

Nuget Package Manager

Adding ASP.NET Identification

First I will sum up all files that are required for ASP.NET Identification. After that I will explain their purpose one by one.

Required files

  • Startup.cs
  • Startup.Auth
  • IdentityModels
  • IdentityConfig
  • AccountController
  • AccountViewModels
  • Views/Account

Startup.cs

This file is located in the root of your application and is required. Every OWIN application has a startup class where you specify components for the application pipeline. OWIN is a specification that defines an API for framework and servers to cooperation. The point of OWIN is to decouple server and application. For example, ASP.NET Identity uses OWIN security, therefore they need to have a startup class, that is defined in “Startup.cs” file.

App_Start/Startup.Auth.cs

This file is an extension (other partial) of the Startup class in Startup.cs. It contains the method ConfigureAuth which is called in the file Startup.cs. If you just need basic functionality the file could look like this:

Models/IdentityModels.cs

 

App_Start/IdentityConfig.cs

In this file you configure the application user manager and signin manager.

And probably you want an EmailService aswell when one of your users forget their password.

 

ViewModels/AcountViewModel.cs

For this basic authentication setup this viewmodel can look like this:

 

AccountController and Views

I recommend you to use the one in the MVC sample project. If you create a new (non-empty) MVC project you will get this class and views for free. Strip all methods you don’t need and adjust the views to your needs.

Now you should be able to compile your project and you can try to login by navigating to /Account/Login

 

More information