C# dotnet 3.1:ChangePasswordAsync提供的密码不匹配,而CheckPasswordAsync接受相同的密码
我正在我的应用程序中的一个部分工作,在那里用户可以更新他们的密码。我在身份验证服务中为此创建了一个方法C# dotnet 3.1:ChangePasswordAsync提供的密码不匹配,而CheckPasswordAsync接受相同的密码,c#,asp.net-core,asp.net-identity,C#,Asp.net Core,Asp.net Identity,我正在我的应用程序中的一个部分工作,在那里用户可以更新他们的密码。我在身份验证服务中为此创建了一个方法 AuthenticationService.cs [Authorize] public async Task ChangePassword(ChangePasswordViewModel model) { // Need to get it this way otherwise the ChangePasswordAsync won't accept this user var
AuthenticationService.cs
[Authorize]
public async Task ChangePassword(ChangePasswordViewModel model)
{
// Need to get it this way otherwise the ChangePasswordAsync won't accept this user
var user = await _userManager.FindByIdAsync(_userService.CurrentUser.Id);
var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
if (!result.Succeeded)
{
throw new Exception();
}
}
[HttpPost]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
try
{
await _authenticationService.ChangePassword(model);
return Ok();
}
catch (Exception)
{
return BadRequest(new ErrorViewModel()
{
ErrorKey = "error_changing_password"
});
}
}
public class ChangePasswordViewModel
{
public string CurrentPassword { get; set; }
public string NewPassword { get; set; }
}
userService.CurrentUser
是一个getter,它使用JWT从IdentityDbContext
获取用户。我进行了调试,结果返回了正确的用户/ID
我从我的AuthenticationController.cs
[Authorize]
public async Task ChangePassword(ChangePasswordViewModel model)
{
// Need to get it this way otherwise the ChangePasswordAsync won't accept this user
var user = await _userManager.FindByIdAsync(_userService.CurrentUser.Id);
var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
if (!result.Succeeded)
{
throw new Exception();
}
}
[HttpPost]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
try
{
await _authenticationService.ChangePassword(model);
return Ok();
}
catch (Exception)
{
return BadRequest(new ErrorViewModel()
{
ErrorKey = "error_changing_password"
});
}
}
public class ChangePasswordViewModel
{
public string CurrentPassword { get; set; }
public string NewPassword { get; set; }
}
但是由于某些原因,ChangePasswordAsync
返回此错误:密码不匹配“
。我绝对肯定这个密码是正确的。我使用它通过相同的用户管理器登录:
await _userManager.CheckPasswordAsync(user, model.Password)
你知道为什么ChangePasswordAsync
会给我这个反馈,而CheckPasswordAsync
会返回一个积极的结果吗?我允许错误的密码吗?我们仅通过UserManager
使用CreateAsync
(创建时)或使用带有生成令牌的ResetPasswordAsync
设置密码。您可以将wait\u UserManager.CheckPasswordAsync(user,model.CurrentPassword)
在您的更改密码
方法中,在结果
之前查看它是否为真。@Yinqiu我这样做了,发生了最奇怪的事情。当我在ChangePasswordAsync
上方使用CheckPasswordAsync
时,它确实可以工作。它会更改密码。当我注释掉它并再次编译时,ChangePasswordAsync
失败。我猜CheckPasswordAsync
修改了用户
,但文档中没有说明这一点。您可以尝试添加此代码wait\u-signInManager.RefreshSignInAsync(用户)代码>更改密码后。