How to save new record with hashed password in my custom table instead of aspnet user?

两盒软妹~` 提交于 2019-12-01 15:15:39

The inconsistency i found, in ApplicationUser class you are declaring property Idand Email which is wrong because the IdentityUser class already have those properties. This may arise the issue. But you can override them if necessary. Also the constructor you are using isn't necessary. The ApplicationUser class should be:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        this.SecurityStamp = Guid.NewGuid().ToString();
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }    
    public string Password { get; set; }
    public string Role { get; set; }
    public bool? IsActive { get; set; }
    public int? CreatedBy { get; set; }
    public DateTime? CreatedDate { get; set; }
    public DateTime? LastLogin { get; set; }

}

Second thing, you are creating the user inside Login action which is also not valid. you should do it inside Register action. Following in an example:

 public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
          var user = new ApplicationUser
            {
                FirstName = "Abc",
                LastName = "Pqr",
                UserName = "Abc@yahoo.com",
                Email= model.Email,
                Password= model.Password,
                PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password),
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var result = await UserManager.CreateAsync(user);
        if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);                    
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        return View(model);
    }

Hope this will help :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!