【问题标题】:Identity Framework create a new password for a user (without a password)身份框架为用户创建一个新密码(没有密码)
【发布时间】:2015-06-11 19:45:11
【问题描述】:

所以,我有这个网站,用户只能由管理员创建。 我这样设置我的 Web API 方法:

/// <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));
}

如您所见,用户是在没有密码的情况下创建的,并且会向新用户发送一封确认电子邮件。 我想用这封确认邮件为用户创建密码,所以我设置了这个方法:

/// <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();
}

问题是将一个空字符串传递给 ChangePasswordAsync 方法抱怨提供的密码不正确。

有人知道如何解决我的问题吗?

【问题讨论】:

  • 在那里获取 AutoMapper,以减少所有 DTO => 域。这可能违反了 Jimmy Bogard 的建议,但是嘿。
  • 你试过null而不是ChangePasswordAsync中的空字符串吗?
  • 我认为您没有为用户创建密码,您需要为该用户传递CreateAsync 密码。否则,您需要在为该用户创建密码的UserManager 上调用AddPasswordAsync
  • AddPasswordAsync 是答案 :) 甚至没有看到那个方法。

标签: c# asp.net-web-api asp.net-identity


【解决方案1】:
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();
}

基本上CreateUser 有两个重载,一个有密码,一个没有。如果您创建一个没有密码的用户,那么您需要使用AddPassword。否则你可以使用ChangePassword

MSDN Reference

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 2016-06-11
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2017-06-19
    • 2011-07-04
    • 2016-02-19
    • 1970-01-01
    相关资源
    最近更新 更多