[英]Web API ChangePasswordAsync controller returning Failed : PasswordMismatch C#
我正在構建一個.net core 2 Identity應用程序。 它為Vuejs前端使用JWT令牌。
我正在編寫更新密碼控制器,該控制器首先檢查令牌,然后使用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");
}
}
通過使用以下方法解決了它:
var user = await _userManager.FindByNameAsync(...);
然后將其傳遞到ChangePasswordAsync
var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword);
錯誤“ {Failed:PasswordMismatch}”是由於您傳入的“ currentPassword”參數與您作為“ model.Password”發送的該用戶(方法中的第二個參數)的現有密碼不匹配。 該方法將驗證此值,以確保用戶就是他們所說的真實身份。
public virtual Task<IdentityResult> ChangePasswordAsync(TUser user, string
currentPassword, string newPassword);
我建議進行調試,以確保您傳遞的是用戶當前密碼,而不是新密碼,並確保您檢索到正確的用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.