#TIL: ASP.NET Identity and Entity Framework

Reviewing an article for a friend and fellow ASP.NET MVP, James Chambers, I actually learned something – ASP.NET Identity comes with some Entity Framework-compatible hooks that allow you to quickly spin up a user & role store with a few lines of code.

The newer versions of ASP.NET have moved to an identity model that doesn’t use the traditional “membership provider” classes of the past, but rather introduce a new concept of a IUser and IUserStore. Using these new interface-based membership mechanisms allows you to roll your own implementation, test your code much easier, and of course take advantage of any implementations that may exist.

The only thing an IUser needs is an ID and Name property. ID is also specified as a string, so you can use a Guid, integer, or whatever works with your existing system. An IUserStore is responsible for the create / read / update / delete functionality when it comes to your user accounts. There are a number of other interfaces as well, ranging from IUserClaimStore to IUserRoleStore, that allow you to fine-tune your authorization and authentication flows.

Of course we need some concrete classes – we don’t want to have to redefine this basic functionality every time we make a new application. The UserManager class gives you most of this functionality, including managing users, changing passwords, managing claims, and adding and removing roles to user accounts.

In addition we have the Entity Framework implementation of the new membership interfaces, in the Microsoft.AspNet.Identity.EntityFramework namespace (available from NuGet). These classes simply implement the I*Store interfaces, providing entity-framework specific implementations of the object-relational mapping for membership objects. With this you can easily create and use membership tables inside your existing data stores, using concepts like code-first development. It’s as simple as putting the following one line of code in your DbInitializer:

var userManager = new UserManager<MyUserClass>(
  new UserStore<MyUserClass>(context));

And there you have it! For more information, check out this tutorial.