Reputation: 2942
I'm currently working from this excellent guide for the purpose of migrating an existing web app that uses SQL Membership authentication to ASP.NET Identity authentication:
With the difference being that I am not using a Web Forms project, so I've adapted it to work with an MVC 5 project. Here's my UserManager class, which is supposed to check for SQL Membership passwords and update them when necessary (see link above for details):
public class MyUserManager : UserManager<ApplicationUser>
{
public MyUserManager()
: base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
{
this.PasswordHasher = new SQLPasswordHasher();
}
public class SQLPasswordHasher : PasswordHasher
{
public override string HashPassword(string password)
{
return base.HashPassword(password);
}
public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
{
string[] passwordProperties = hashedPassword.Split('|');
[SNIP]
The problem is that the /Account/Login method does not seem to use the PasswordHasher extension. Here's the code (straight from the MVC 5 template, though the UserManager object is an instance of the MyUserManager class above):
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
[SNIP]
It won't authenticate. I imagine I'm not the only one trying to make this work. Any pointers? For MVC 5, do I need to write a different extension?
Thanks for any help you can provide.
Upvotes: 1
Views: 10684
Reputation: 2942
Here is the way this should be set up for a new MVC 5 project:
IdentityModels.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("ApplicationServices")
{
}
}
public class MyUserManager : UserManager<ApplicationUser>
{
public MyUserManager()
: base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
{
this.PasswordHasher = new SQLPasswordHasher();
}
public class SQLPasswordHasher : PasswordHasher
[etc.]
The SQLPasswordHasher code can be found here.
AccountController.cs
public class AccountController : Controller
{
public AccountController()
: this(new MyUserManager())
{
}
public AccountController(MyUserManager userManager)
{
UserManager = userManager;
}
public MyUserManager UserManager { get; private set; }
[etc.]
The rest is exactly as it appears on the blog mentioned above and/or as it appears in the default MVC 5 template. Once hooked up to a context with SQL Membership info, it works like a charm. Hope this helps.
Upvotes: 3