I have seen lots of similar pages on the web, but most of them use a new project instead of an existing one, or don't have the necessary features. So, I have an existing MVC 5
project and want to integrate ASP.NET MVC5 Identity with log in, email confirmation and password reset features.
In addition to this, I also need to create all the necessary tables on the database i.e. User, Roles, groups, etc. (I use EF Code First in my project). Is there an article or sample that corresponds to these needs?
Best Answer
Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.
First install these NuGet packages with Package Manager Console:
Add a user class and with
IdentityUser
inheritance:Do same thing for role:
Change your
DbContext
parent fromDbContext
toIdentityDbContext<AppUser>
like this:If you use the same connection string and enabled migration, EF will create necessary tables for you.
Optionally, you could extend
UserManager
to add your desired configuration and customization:Since Identity is based on OWIN you need to configure OWIN too:
Add a class to
App_Start
folder (or anywhere else if you want). This class is used by OWIN. This will be your startup class.Almost done just add this line of code to your
web.config
file so OWIN could find your startup class.Now in entire project you could use Identity just like any new project had already installed by VS. Consider login action for example
You could make roles and add to your users:
You could also add a role to a user, like this:
By using
Authorize
you could guard your actions or controllers:or
You can also install additional packages and configure them to meet your requirement like
Microsoft.Owin.Security.Facebook
or whichever you want.Note: Don't forget to add relevant namespaces to your files:
You could also see my other answers like this and this for advanced use of Identity.