Web API ChangePasswordAsync控制器返回失败:PasswordMismatch C#

问题描述 投票:0回答:2

我正在构建.net核心2身份应用程序。它使用JWT令牌作为Vuejs前端。

我正在编写更新密码控制器,首先检查令牌,然后使用ChangePasswordAsync更改密码,但我一直得到响应:

{Failed : PasswordMismatch}.

我的控制器代码如下。我已成功编写了登录和注册控制器,但没有运气。登录用户ctrustUser已成功返回,因此我使用该数据将登录的用户数据传递给ChangePasswordAsync。请你帮帮我。

  [Authorize(Policy = "ApiUser")]
  [Route("api/[controller]/[action]")]
  public class AccountsEditController : Controller
  {
    private readonly ClaimsPrincipal _caller;
    private readonly ApplicationCtrustUsersDbContext _appDbContext;
    private readonly UserManager<AppAdminUser> _userManager;
    private readonly IMapper _mapper;

    public AccountsEditController(UserManager<AppAdminUser> userManager, ApplicationCtrustUsersDbContext appDbContext, IHttpContextAccessor httpContextAccessor, IMapper mapper)
    {
      _userManager = userManager;
      _caller = httpContextAccessor.HttpContext.User;
      _appDbContext = appDbContext;
      _mapper = mapper;
    }

    // POST api/accountsedit/updatepassword
    [HttpPost]
    public async Task<IActionResult>UpdatePassword([FromBody]UpdatePasswordViewModel model)
    {
      // simulate slightly longer running operation to show UI state change
      await Task.Delay(250);

      if (!ModelState.IsValid)
      {
        return BadRequest(ModelState);
      }

      // retrieve the user info
      var userId = _caller.Claims.Single(c => c.Type == "id");
      var ctrustUser = await _appDbContext.CtrustUser.Include(c => c.Identity).SingleAsync(c => c.Identity.Id == userId.Value);

      AppAdminUser userIdentity = new AppAdminUser();

      userIdentity.Id = ctrustUser.IdentityId;
      userIdentity.UserName = ctrustUser.Identity.UserName;
      userIdentity.Email = ctrustUser.Identity.Email;

      //AppAdminUser user = _mapper.Map<AppAdminUser>(model);

      var result = await _userManager.ChangePasswordAsync(userIdentity, model.Password, model.NewPassword);

      if (!result.Succeeded) return new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState));

      return new OkObjectResult("Password updated");
    }
  }
c# asp.net-core asp.net-core-identity
2个回答
1
投票

解决了它,使用:

var user = await _userManager.FindByNameAsync(...);

然后将其传递给ChangePasswordAsync

var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword); 

0
投票

错误{Failed:PasswordMismatch}是由于您传入的“currentPassword”参数与该用户的现有密码(方法中的第二个参数)不匹配,您将其作为“model.Password”发送。该方法验证此值以确保用户是他们所说的人。

public virtual Task<IdentityResult> ChangePasswordAsync(TUser user, string 
    currentPassword, string newPassword);

我建议调试它以确保您传入用户当前密码,而不是新密码,并确保您正在检索正确的用户。

© www.soinside.com 2019 - 2024. All rights reserved.