Tags

, , , , , , , ,

ASP.NET Identity is the newest framework for authentication and authorization of users provided by Microsoft. The good news is that it is fairly easy to convert our existing web applications from membership to ASP.NET Identity.

 

Below are the changes that are required to convert your application to use ASP.NET Identity. Please note that you can do all the work in your presentation layer as well, but I prefer to separate the tasks into layers for separation of concerns.

Data Access Layer

In DAL project, we must install Microsoft.AspNet.Identity.EntityFramework package through nuGet before proceeding. Once installed, we create a new user class that inherits from IdentityUser.

internal class AdventureWorks2012User : IdentityUser
{
}
 
 
 

Next, we create the DbContext.

internal class UserSecurityDbContext
IdentityDbContext<AdventureWorks2012User>
{
public UserSecurityDbContext() : base(“LoginConnection”)
{
}
}
 
 
 

And finally, we create the Repository. Since UserManager is tightly coupled to DbContext, so I decided to keep the entire logic within the repository and just return the result.

public class UserSecurityRepository : BaseEFRepository
{
private readonly UserManager<AdventureWorks2012User> UserManager;
 
/// <summary>
/// Default Constructor
/// </summary>
public UserSecurityRepository()
{
UserManager = new UserManager<AdventureWorks2012User>(new UserStore<AdventureWorks2012User>(new UserSecurityDbContext()));
}

/// <summary>

/// Validates the user and returns ClaimsIdentity if successful
/// </summary>
/// <param name=”username”></param>
/// <param name=”password”></param>
/// <param name=”authenticationTypes”></param>
/// <returns></returns>
public async Task<ClaimsIdentity> ValidateUser(string username, string password, string authenticationTypes)
{
AdventureWorks2012User user = await UserManager.FindAsync(username, password);

if (user != null)

{
return await UserManager.CreateIdentityAsync(user, authenticationTypes);
}

return null;

}
} 
 
 
 
 

ASP.NET MVC Project

In our ASP.NET MVC project, we need to install the below packages.

Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Host.SystemWeb
 
 
 

After that, we create the Startup class for configuring OWIN authentication.

[assembly:Microsoft.Owin.OwinStartup(typeof(SajidQ.Net.AdventureWorks2012.UI.Web.Mvc5.Startup))]
namespace SajidQ.Net.AdventureWorks2012.UI.Web.Mvc5
{
/// <summary>
/// Startup class for OWIN
/// </summary>
public class Startup
{
/// <summary>
/// Sets OWIN configuration
/// </summary>
/// <param name=”app”></param>
public void Configuration(Owin.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);
}
}
}
 
 

This will configure our application to authenticate the request before proceeding. It will basically look for authentication cookie. If it is not present, request will be redirected to the login page.

Our Login POST action will validate the request through DAL and on success, would sign-in.

 
/// <summary>
/// POST action for Login
/// </summary>
/// <param name=”model”></param>
/// <param name=”returnUrl”></param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
ClaimsIdentity identity = await new UserSecurityRepository().ValidateUser(model.Username, model.Password, DefaultAuthenticationTypes.ApplicationCookie);

if (identity != null)

{
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties IsPersistent = model.RememberMe }, identity);
return RedirectToLocal(returnUrl);
}
ModelState.AddModelError(“”, “Invalid username or password.”);
}

// If we got this far, something failed, redisplay form

return View(model);
}
 
  
 

In our web.config file, we have to disable authentication, since it will be handled through OWIN.

<authentication mode=None />

 
 

After these changes, our application would be ready with ASP.NET Identity. In the database, we should see the below tables.

 
 
 

I added a new user “sajidq” with a single role of “Administrator”.


About these ads