Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Identity, Register manual added user without deleting him

I have an issue with ASP.NET Identity. In my application, I want to add users to the table dbo.AspNetUsers, as soon as someone adds them to a poll with their mail adress, like this:

var user = new ApplicationUser
            {
                UserName = model.Email,
                Email = model.Email,
                TwoFactorEnabled = false,
                EmailConfirmed = false,
                Registered = true
             };
 _dbContext.ApplicationUsers.Add(user);
 _dbContext.SaveChanges();

If someone who was added like this to the database earlier, wants to register himself with his mailadress, I don't want to delete the manually added user and register him as a new one, because other relations are already related to his ID and constraints would not allow that. I also can not delete the connected relations, because other users are also related to them.

I tried to manually add a hashedPassword to him in the database like this:

 _dbContext.ApplicationUsers.FirstOrDefault(u => u.Email == model.Email).PasswordHash =
                this.HashPassword(user, model.Password);
 _dbContext.SaveChanges();

But then the login failed, because of an internal server error, because of a NULL value in "System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue)".

Does someone know a solution to register a user, who was already added manually, without deleting him?

Thanks for answers!

EDIT/SOLUTION

Here is the solution:

In a first step, just create the user with a default password, then if he wants to register, remove the Password and add the Password from the RegisterModel, like this:

var result = await _userManager.CreateAsync(user, "DefaultPassword1.");

await _userManager.RemovePasswordAsync(user);
var result = await _userManager.AddPasswordAsync(user, model.Password);
like image 962
davidrue Avatar asked Jan 28 '26 01:01

davidrue


1 Answers

If you look in the Manage Controller you'll see all the methods to manage user accounts. For example to add a password you'd use

var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
like image 174
Matthew Avatar answered Jan 30 '26 15:01

Matthew