在ASP.NET MVC5中的密码恢复

7

我是一名工作在ASP.NET MVC 5应用程序中的技术人员。用户能够顺利注册和登录。但是当有一个用户忘记了他/她的密码时,已经存在的忘记密码流程没有起到任何作用!没有邮件被发送给用户,带有“单击此处重置密码”的链接。

当前我的ForgotPassword操作方法如下:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindByNameAsync(model.Email);
        if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

我猜这需要开发人员来实现。我在谷歌上搜索了一下,没有找到直接的方法。

最简单的方法是什么?

1个回答

8

忘记密码操作生成重置令牌:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindByNameAsync(model.Email);
        if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }

        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
        // Send an email with this link
        string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);      
        await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
        return RedirectToAction("ForgotPasswordConfirmation", "Account");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

通过生成的令牌重设密码的操作:

[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
    return code == null ? View("Error") : View();
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    var user = await UserManager.FindByNameAsync(model.Email);
    if (user == null)
    {
        // Don't reveal that the user does not exist
        return RedirectToAction("ResetPasswordConfirmation", "Account");
    }
    var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
    if (result.Succeeded)
    {
        return RedirectToAction("ResetPasswordConfirmation", "Account");
    }
    AddErrors(result);
    return View();
}

相关视图模型:

public class ResetPasswordViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
    public string Code { get; set; }
}

public class ForgotPasswordViewModel
{
    public string Email { get; set; }
}

在发送电子邮件之前,您需要配置电子邮件服务。

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        return configSendGridasync(message);
    }

    private Task configSendGridasync(IdentityMessage message)
    {
        var myMessage = new SendGridMessage();
        myMessage.AddTo(message.Destination);
        myMessage.From = new System.Net.Mail.MailAddress(
                      "you@somewhere.com", "My name");
        myMessage.Subject = message.Subject;
        myMessage.Text = message.Body;
        myMessage.Html = message.Body;

        var credentials = new NetworkCredential("userName","Password");

        // Create a Web transport for sending email.
        var transportWeb = new Web(credentials);

       // Send the email.
       if (transportWeb != null)
       {
           return transportWeb.DeliverAsync(myMessage);
       }
       else
       {
           return Task.FromResult(0);
       }
   }
}

在最后,你需要在用户管理器的配置器中注册这个身份类Identity,并添加以下行:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

    // some code here

    manager.EmailService = new EmailService();
}

请查看ASP.NET Identity(C#)的账户确认和密码恢复,这是一个逐步教程。


谢谢@SamFarajpourGhamari,我认为await UserManager.SendEmailAsync()出了问题,因为我仍然没有收到任何电子邮件! - J86
1
您还需要配置电子邮件服务。请查看我的更新帖子。 - Sam FarajpourGhamari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接