Adding ASP.NET Identity 4.5 to an Existing Application
Watching videos about putting ASP.NET websites together, it always looks really nice and straight forward, it demos really well. Back at the office, faced with some real world requirements things never seem that simple. To this end I decided to try to setup the Identity framework from scratch on an existing web application.
The following stackoverflow links explain this in detail, but as I implemented it myself on a test app I thought to document it here:
Step 1, install the necessary packages:
Install-Package Microsoft.AspNet.Identity.Owin
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.Owin.Host.SystemWeb
Its not required to create a UserManager, but it does provide us with the option to customise the setup:
The following stackoverflow links explain this in detail, but as I implemented it myself on a test app I thought to document it here:
- Adding ASP.NET MVC5 Identity Authentication to an existing project
- How can I change the table names when using Visual Studio 2013 AspNet Identity
- Introduction to ASP.NET Identity
Install Packages
Step 1, install the necessary packages:
Install-Package Microsoft.AspNet.Identity.Owin
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.Owin.Host.SystemWeb
Create Entities
The IdentityDbContext includes entities for Users and Roles but we can customize them by extending the builtin objects.
Update Application EF Context
The three things to note here are:
- The context now extends the IdentityDbContext<User> context
- The OnModelCreatingMethod renames the tables so they're not all prefixed with "AspNet"
- The context connection is now passed in through the constructor, else it tries to use DefaultConnection.
Create a UserManager
Its not required to create a UserManager, but it does provide us with the option to customise the setup:
Add Owin Configuration
The Identity classes uses Owin, so we need to setup the configuration for the Identity owing provider.
And finally
Once all setup, and if automatic migrations aren't turned on, then you need to run Add-migration and Update-database to create a migration and run it againest your database.