Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using asp.net identity to create new user but getting error:

Cannot insert the value NULL into column 'Id', table 'Mydb.dbo.AspNetUsers'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated

But here I don't have any such table like AspNetUsers but instead I have my own table that is Users.

Code: Web.config: 2 conection strings

 <add name="myEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=;initial catalog=mydb;user id=sa;password=sdfsdfsdf;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
 <add name="MyConnString" connectionString="data source=;initial catalog=Mydb;user id=sa;password=sdfsdfsdf;" providerName="System.Data.SqlClient" />

IdentityModel.cs:

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 Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public virtual string Email { get; set; }
        public string Password { get; set; }
        public string Role { get; set; }
        public Nullable<bool> IsActive { get; set; }
        public Nullable<int> CreatedBy { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public Nullable<System.DateTime> LastLogin { get; set; }

        public ApplicationUser()
        {

        }

        public ApplicationUser(string email, string firstName, string lastName, string designation, bool isActive)
        {
            Email = email;
            FirstName = firstName;
            LastName = lastName;
            Designation = designation;
            IsActive = isActive;
        }
    }
  public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("MyConnString", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

UserStore1.cs:

public class UserStore1 : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>
    {
        private readonly HttpContext _httpContext;
        UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(new ApplicationDbContext());

        public System.Threading.Tasks.Task CreateAsync(ApplicationUser user)
        {
            HttpContext.Current = _httpContext ?? HttpContext.Current;
            var context = userStore.Context as ApplicationDbContext;
           context.Users.Add(user);
           context.Configuration.ValidateOnSaveEnabled = false;
           context.SaveChanges();
            return Task.FromResult(true);
        }
     }

Controller:

     [Authorize]
    public class AccountController : Controller
    {
        public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore1()))
        {
        }

        public AccountController(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }
        public UserManager<ApplicationUser> UserManager { get; private set; }
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(string email, string password, bool rememberMe = false, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName= "Abc",
                    LastName= "Pqr",
                    UserName="[email protected]",
                    SecurityStamp = Guid.NewGuid().ToString()
                };

                var result= await UserManager.CreateAsync(user,"123456");
            }
            return View();
        }
    }

Note: I have autogenerated Id in my database table field and that Id is Int.

Update: I am using database first(edmx) and the table that I am using are custom tables for inserting new records(for eg:Users).

At first I have implemented microsoft asp.net identity as shown in below question but 1 user pointed out that I am not using ApplicationUser class which is responsible for handling sign in,cookies etc so I am now trying to use ApplicationUser class:

How to give custom implementation of UpdateAsync method of asp.net identity?

I am really now regretting over my decision to choose Microsoft Identity Framework for Authentication purpose as because I am really finding it complex but now as I have move forward I have to go with it.

like image 597
Learning-Overthinker-Confused Avatar asked Sep 03 '16 07:09

Learning-Overthinker-Confused


1 Answers

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 = "[email protected]",
                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 :)

like image 82
Mahbubur Rahman Avatar answered Nov 02 '22 17:11

Mahbubur Rahman