Adding MVC 5 Identity to an Existing Project

From Logic Wiki
Jump to: navigation, search


Install-Package Microsoft.AspNet.Identity.Core 
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.AspNet.Identity.Owin 
Install-Package Microsoft.Owin.Security.Facebook
Install-Package Microsoft.Owin.Security.Google
Install-Package Microsoft.Owin.Security.MicrosoftAccount
Install-Package Microsoft.Owin.Security.Twitter
Install-Package Microsoft.AspNet.WebApi.Client 
Install-Package Microsoft.Owin.Host.SystemWeb

Install-Package Microsoft.Owin.Security.OAuth 
Install-Package Microsoft.Owin.Security.Cookies

That should be all the NuGet references you need to install. Now let’s create the files that make up Visual Studio 2013’s MVC 5 Web Application’s Account Login and Registration System.

We will start in the App_Start folder and make our way down.

1) Right click on App_Start folder and Add > Class. Name it: FilterConfig.cs place the following code in your file:

using System.Web;
using System.Web.Mvc;
 
namespace MVC5FullApp
{
  public class FilterConfig
  {
    public static void RegisterGlobalFilters(GlobalFilterCollection   filters)
    {
      filters.Add(new HandleErrorAttribute());
    }
  }
}

2) Right click on App_Start folder and Add > Class. Name it: Startup.Auth.cs Dont forget the dot between Startup & Auth “Startup.Auth.cs” place the following code in your file:

using System.Web;
using System.Web.Mvc;
 
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
 
namespace MVC5FullApp
{
  public partial class Startup
  {
  // For more information on configuring authentication, please visit   http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
    // Enable the application to use a cookie to store information for the signed in user
      app.UseCookieAuthentication(new CookieAuthenticationOptions
      {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login")
      });
      // Use a cookie to temporarily store information about a user logging in with a third party login provider
       
 app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
 
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
 
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
 
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
 
//app.UseGoogleAuthentication();
    }
  }
}

The rest of the code for this project I am going to simply put in a .Zip file and let you install manually, because it is too much code to put on the tutorial. Simply extract the .zip file and copy the files from the Controllers folder to the controllers folder in your project, and so on.

Identity_Tut_Files

So I simply opened up the folder of this Zip File and drag & Dropped them into the solution. I did not have to include the files, Visual Studio made them available upon dropping them in.

Ok we should have all of those files in the project now, go through each one and open them one by one and make sure there are no errors or squiggly lines. If we did our job at providing all of the right references before dropping these files in there should be no errors.

We still need to add one more file, we can do this manually. Right Click on the root directory and add a class. Name it Startup.cs Inside that file put the following code:
<pre class="brush:csharp;">
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(MVC5FullApp.Startup))]
namespace MVC5FullApp
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}

That should allow us to build and run our project.

Now our project is working with Identity, OWIN, the account pages work, but we need a link in our navigation to them.

Let’s go to our _LoginPartial.cshtml and remove the bootstrap code and add our foundation code so that it works in our navigation. Let’s just replace the code from @if (Request.IsAuthenticated) to the bottom of the page with:

@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "right" }))
{
@Html.AntiForgeryToken()
 
<li class="has-dropdown">
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
 
<ul class="dropdown">
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
</li>
}
}
else
{
<li class="has-dropdown">
@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })
 
<ul class="dropdown">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
</li>
}

Now let’s uncomment the line we have in our navigation that loads the LoginPartial. It’s in the _Foundation.cshtml file. Just uncomment it and we are good to go. Build and run your site. YOu should have a login button on your navigation that once logged in will have a dropdown with options. Were done, you will need to format those login and registration pages, but the hard work is done!