Modelbinding a hashed password in ASP.NET MVC 3 with Entity Framework 4.1
I'm trying to create an ASP.NET MVC application using Entity Framework 4.1's code-first approach and I'm a little confused as to how to handle validation in the following scenario:
Let's say I have a simple User class using DataAnnotations for validation:
public class User
{
public int UserId { get; set; }
[Required]
[StringLength(500)]
public string Email { get; set; }
[Required]
[StringLength(50)]
public string Salt { get; set; }
[Required]
[StringLength(50)]
public string HashedPassword { get; set; }
public void SetPassword(string password)
{
if (string.IsNullOrWhiteSpace(Salt))
Salt = Guid.NewGuid().ToString();
HashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Concat(password, Salt), "sha1");
}
}
Note that the intent here is for callers to use the SetPassword routine to set the password on a User object. This will autogenerate the Salt if one doesn't exist and use it to hash the password for storing into the database.
Now, let's say I create a UsersController like this:
public class UsersController : Controller
{
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(User user)
{
if (!ModelState.IsValid)
return View(user);
// Save user to database
return RedirectToAction("Index", "Home");
}
}
开发者_运维技巧
My questions are:
- My form is going to have fields for the username, email, and password. The username and email should map to the "user" just fine via the default model binder. But how do I get the model binder to take the inputted password and call my SetPassword function with it? Do I need to use a custom model binder for this? If so, how do I ensure the DataAnnotation validations still execute?
- I'd really like for the Salt and HashedPassword properties on my User class to be readonly. Is there a way to do this that still allows for Entity Framework to set these properties when loading a User from the database?
Ideally the process of generating the password does not belong in the ViewModel, it should be part of your domain model. The default model binder needs the data used to be filled into the model to be available in the FormsCollection when a form post happens.
精彩评论