Identity Framework create a new password for a user (without a password)

1.5k Views Asked by At

So, I have this site where users can only be created by administrators. I set up my Web API method like this:

/// <summary>
/// Creates a user (with password)
/// </summary>
/// <param name="model">The bound user model</param>
/// <returns></returns>
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CreateUser(UserBindingModel model)
{

    // If our ModelState is invalid, return a bad request
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Get the current userId and date
    var userId = User.Identity.GetUserId();
    var date = DateTime.UtcNow;

    // Assign our binding model to a new model
    var user = new User()
    {
        CompanyId = model.CompanyId,
        UserName = model.Email,
        Email = model.Email,
        FirstName = model.FirstName,
        LastName = model.LastName,
        LastLoginDate = date,
        Telephone = model.Telephone,

        CreatedById = userId,
        ModifiedById = userId,
        DateCreated = date,
        DateModified = date
    };

    // Try to create the user
    var result = await this.UserService.CreateAsync(user);

    // If the creation fails, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Send the confimation email
    await SendConfirmationEmail(user.Id);

    // Get the location header
    var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

    // Return the result
    return Created(locationHeader, this.ModelFactory.Create(user));
}

As you can see, the user is created without a password and a confirmation email is sent to the new user. I want to use this confirmation email to create a password for the user, so I set up this method:

/// <summary>
/// Used to confirm the users email address
/// </summary>
/// <param name="userId">The user id of the user to confirm</param>
/// <param name="code">The generated code that was sent to the email address</param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
[Route("Confirm", Name = "ConfirmEmailRoute")]
public async Task<IHttpActionResult> ConfirmEmail(ConfirmBindingModel model)
{

    // If our userId or code are not supplied
    if (string.IsNullOrWhiteSpace(model.UserId) || string.IsNullOrWhiteSpace(model.Code))
    {

        // Add an error message to the ModelState
        ModelState.AddModelError("", "User Id and Code are required");

        // And return a BadRequest with the attached ModelState
        return BadRequest(ModelState);
    }

    // Set our password
    var result = await this.UserService.ChangePasswordAsync(model.UserId, "", model.Password);

    // If we didn't manage to create a password, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Confirm our user
    result = await this.UserService.ConfirmEmailAsync(model.UserId, model.Code);

    // If we didn't manage to confirm the user, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // If we reach this point, everything was successful
    return Ok();
}

The problem is passing an empty string to the ChangePasswordAsync method complains that the password supplied is incorrect.

Does anyone know how I can solve my issue?

1

There are 1 best solutions below

0
On BEST ANSWER
public async Task<IHttpActionResult> ConfirmEmail(ConfirmBindingModel model)
{

    // If our userId or code are not supplied
    if (string.IsNullOrWhiteSpace(model.UserId) || string.IsNullOrWhiteSpace(model.Code))
    {

        // Add an error message to the ModelState
        ModelState.AddModelError("", "User Id and Code are required");

        // And return a BadRequest with the attached ModelState
        return BadRequest(ModelState);
    }

    //<--- in your create user method you set not password so this won't work
    // Set our password
    // var result = await this.UserService.ChangePasswordAsync(model.UserId, "", model.Password);

    //<--- instead you need to use AddPasswordAsync ----->
    var result = await this.UserService.AddPasswordAsync(model.UserId, model.Password);

    // If we didn't manage to create a password, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Confirm our user
    result = await this.UserService.ConfirmEmailAsync(model.UserId, model.Code);

    // If we didn't manage to confirm the user, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // If we reach this point, everything was successful
    return Ok();
}

Basically CreateUser has two overloads, one with password, one without. If you create a user without a password then you need to use AddPassword. Otherwise you can use ChangePassword

MSDN Reference