Is it possible to use additional user fields for user login in .Net Core Identity? I want to allow logging in users using email, password, and a third field i.e Company Name
which is a custom field I defined in ApplicationUser class
inherited from IdentityUser class
.
My ApplictionUser class:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CompanyName { get; set; }
}
It is working fine. I can add the company name for the user during registration.
Here is the identity InputModel code which is created by identity scaffolding:
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
I added the CompanyName extra field here. Now I want to log in the user based on these fields. If the company name provided by the user on the login page is correct, allow the user to login otherwise not.
I am doing the following custom code inside OnPostAsync method
of Login.cshtml.cs
file:
var user = await _userManager.FindByEmailAsync(Input.Email);
ApplicationUser user = new ApplicationUser
{
Email = Input.Email,
UserName = Input.Email,
CompanyName = Input.CompanyName,
};
var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: false);
But the result is always getting failed for every attempt. Am doing anything wrong here?
You appear to be overwriting the user
object with your new implementation, which wouldn't have the password hash to check against (amongst other things).
It may be simpler to check the user
for the correct company name directly and throw the error if it doesn't match, as follows:
var user = await _userManager.FindByEmailAsync(Input.Email);
if (user == null || user.CompanyName != Input.CompanyName) {
ModelState.AddModelError("", "Invalid login attempt");
return View(model);
}
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);