epv epv - 1 month ago 25
C# Question

Changing ASP.NET Identity Password

I have a class that creates a user by searching for the email and making sure it doesn't exist and it creates a user:

public async Task EnsureSeedDataAsync()
{
if (await _userManager.FindByEmailAsync("test@theworld.com") == null)
{
// Add the user.
var newUser = new CRAMSUser()
{
UserName = "test",
Email = "test@crams.com"
};

await _userManager.CreateAsync(newUser, "P@ssw0rd!");
}
}


I am trying create another class to change the password, with the same method but I am confused as to how to create a currentUser object to be passed into the RemovePassword and AddPassword calls. This is what I have so far :

public async Task ChangePassword()
{
if (await _userManager.FindByEmailAsync("test@theworld.com") != null)
{
_userManager.RemovePasswordAsync(currentUser);

_userManager.AddPasswordAsync(currentUser, "newPassword");
}
}


Can someone please direct me in the right direction as I am new to this and don't know how to transfer the currentUser object, that contains the email that is being searched.

Answer

FindByEmailAsyc returns the user object, you need to save it to a variable and pass that to the other userManager calls. Also, the RemovePassword and AddPassword methods take the key value of your User object as a parameter, not the whole User object.

public async Task ChangePassword()
{

    var currentUser = await _userManager.FindByEmailAsync("test@theworld.com") 
    if (currentUser != null)
    {
        _userManager.RemovePasswordAsync(currentUser.Id);

        _userManager.AddPasswordAsync(currentUser.Id, "newPassword");
    }
}