I have wired up my application to use ASP.NET Identity
in an ASP.NET MVC
environment, and it works great. I love it. But I have an issue with the field it uses;
Specifically, the login
method.
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[Route("account/login")]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {
if (ModelState.IsValid) {
var user = await UserService.FindAsync(model.UserName, model.Password);
if (user != null) {
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else {
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
private async Task SignInAsync(Member user, bool isPersistent) {
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserService.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(
new AuthenticationProperties() {
IsPersistent = isPersistent
},
identity);
}
This creates an authentication ticket using the UserName
field of the Member
class that is coded against the IUser
system. Now, that does work, but I want it to use the Email
field.
The reason is because I use User.Identity.Name
for some things, and I really want it to equal the value in the Email
field.
Unfortunately, there is no Email
field on IUser
. I'm having a hard time figuring out how to do this. Right now, I am doing it by setting UserName to always get or set the Email field, like this.
public class Member : IUser {
// ...
public string Email { get; set; }
public string UserName { get { return Email; } set { Email = value; } }
// ...
}
but that's a very 'hacky' way to do it, I'd like to learn a cleaner method.