在我的MVC和Web API项目中,我使用ASP.NET Identity进行登录。
这是我在AccountController上的忘记密码功能:
[HttpPost]
[AllowAnonymous]
[Route("ForgotPassword")]
public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
return Ok();
}
try
{
var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = new Uri(@"http://MyProject/ResetPassword?userid=" + user.Id + "&code=" + code);
string subject = "Reset Password";
string body = "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>";
SendEmail(user.Email, callbackUrl, subject, body);
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
return Ok();
}
// If we got this far, something failed, redisplay form
return BadRequest(ModelState);
}
我收到确认电子邮件,我已成功重定向到重置密码视图,但后来我不确定如何继续。
如何使用以下参数重置密码:NewPssword,ConfirmPassword和Code? p>
很抱歉,如果这是一个愚蠢的问题,但我有点困惑。
我尝试调用SetPassword方法但遇到401错误。
self.resetPassword = function () {
var data = {
Email: self.loginUserName(),
NewPassword: self.registerPassword(),
ConfirmPassword: self.registerPassword2()
}
$.ajax({
type: 'POST',
url: '../API/Account/SetPassword',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
complete: showError
});
}
和setPassword函数:
// POST api/Account/SetPassword
[Route("SetPassword")]
public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
目前该流程如下:
直到这里我编写了代码并将其付诸实践,但我不确定如何实施后续步骤:
提前致谢。
答案 0 :(得分:4)
听起来像你的SetPassword api应该调用
var user = await UserManager.FindByNameAsync(model.Email);
if (user != null)
{
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.NewPassword);
if (result.Succeeded)
{
//handle success
}
}
//handle invalid