我正在构建.net core 2 Identity应用程序。它将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");
}
}
答案 0 :(得分:1)
使用以下方法解决了该问题:
var user = await _userManager.FindByNameAsync(...);
然后将其传递给ChangePasswordAsync
var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword);
答案 1 :(得分:0)
错误{Failed:PasswordMismatch}是由于您传入的“ currentPassword”参数与您以“ model.Password”发送的该用户的现有密码(方法中的第二个参数)不匹配。该方法将验证此值,以确保用户就是他们所说的。
public virtual Task<IdentityResult> ChangePasswordAsync(TUser user, string
currentPassword, string newPassword);
我建议进行调试,以确保您输入的是用户当前密码,而不是新密码,并确保您检索到正确的用户。