samesite


【译】MVC3 20个秘方-(6)找回忘记的密码

问题

你网站的一个用户在你的网站已经注册了,但是他忘记了密码,现在需要一种方式去找回他。

解决方案

为了允许用户去找回他们的密码,必须在AccountController中添加一个新的action和一个新的view。这个功能将使用MemberShip类去寻找一个匹配的用户,并发送一个包含它密码的邮件到他们相关的邮箱。

讨论

默认情况下,MVC Internet Applications 使用的是单向 hash为密码加密。这样,密码不可能被找回。在下边的例子。默认的加密方法使用双向加密。这样虽然不是很安全。但是他避免了强迫那些忘记了密码的用户重置密码

作为开始,我们首先要修改web.config中关于membership的配置。

<?xml version="1.0"?>
<configuration>
...
<system.web>
...
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type=
"System.Web.Security.SqlMembershipProvider"

connectionStringName
="ApplicationServices"
enablePasswordRetrieval
="true" enablePasswordReset=
"false"
requiresQuestionAndAnswer="false"
requiresUniqueEmail
="false" passwordFormat=
"Encrypted"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength
="6"
minRequiredNonalphanumericCharacters
="0"
passwordAttemptWindow
="10" applicationName="/"/>
</providers>
</membership>
<machineKey
validationKey=
"2CF9FF841A23366CFA5D655790D9308656B1F7532C0B95B5C067F80C45E59875
E2F3D68DAC63B5024C31D974D4BE151341FB8A31FC4BC3705DF5398B553FC3C3"

decryptionKey
="8E71407B62F47CCA3AAA6546B3880E1A0EF9833700
E0A0C511710F537E64B8B6"
validation="SHA1" decryption="AES"/>
...
</system.web>
...
</configuration>

上边的代码修改了4个关键的地方:

1. enablePasswordRetrieval 从false改true  。就是可以找回密码。

2. enablePasswordReset was 从true改成false。就是不重置密码。

3. 添加了passwordFormat="Encrypted" 。

4. machineKey 被生成了,用于加密。

在配置完config之后,我们要为Forgot Password view 创建一个model。这个类应该放在AccountModel.cs类中。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
namespace MvcApplication.Models
{
public class ChangePasswordModel
{
...
}
public class LogOnModel
{
...
}
public class RegisterModel
{
...
}
public class ForgotPasswordModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
}
}

在添加新的View之前,先build一下项目。展开View文件夹,右键点击添加->视图。命名为ForgotPassword。因为这个View将是一个强类型的,去对应先前创建的ForgotPasswordModel。

再添加完View以后,在其中添加一个form。它接受用户的Email地址。

@model MvcApplication.Models.ForgotPasswordModel
@{
ViewBag.Title = "ForgotPassword";
}
<h2>ForgotPassword</h2>
1.6 Retrieving a Forgotten Password | 27
<p>
Use the form below to retrieve your password.
</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content(
"
~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Password retrieval was
unsuccessful. Please correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</div>
<p>
<input type="submit" value="Retrieve Password" />
</p>
</fieldset>
</div>
}

然后更新在上一篇文章我们创建的MailClient class。添加一个新的函数。将为用户发送他们忘记的密码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Configuration;
namespace MvcApplication.Utils
{
public class MailClient
{
private static readonly SmtpClient Client;
static MailClient()
{
...
}
private static bool SendMessage(string from, string to,
string subject, string body)
{
...
}
public static bool SendWelcome(string email)
{
...
}
public static bool SendLostPassword(string email,
string password)
{
string body = "Your password is: " + password;
return SendMessage("no-reply@no-reply.com", email,
"Lost Password", body);
}
}
}

这个和前一个非常相似。除了多了第二个参数----用户的密码。密码放在body中,发送给用户。

最终,在这个AccountController中创建2个action。第一个简单的读取之前的view。第二个可以接收post的ForgotPasswordModel。用我们在form中收集到的Email地址,我们可以在Member数据库中找到相应user。然后发送密码给那个email地址。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MvcApplication.Models;
using MvcApplication4.Utils;
namespace MvcApplication4.Controllers
{
public class AccountController : Controller
{
...
//
// Get: /Account/ForgotPassword
public ActionResult ForgotPassword()
{
return View();
}
//
// Post: /Account/ForgotPassword
[HttpPost]
public ActionResult ForgotPassword(
ForgotPasswordModel model)
{
if (ModelState.IsValid)
{
MembershipUserCollection users =
Membership.FindUsersByEmail(model.Email);
if (users.Count > 0)
{
foreach (MembershipUser user in users)
{
MailClient.SendLostPassword(model.Email,
user.GetPassword());
}
return RedirectToAction("LogOn");
}
}
// If we got this far, something failed,
// redisplay form
return View(model);
}
...
}
}

在最近的2个秘方中。基本的邮件已经发送到用户那去了。这些例子可以进一步提高成发送更复杂的邮件。甚至邮件内容可以包括HTML。在Mail Message 类中有一个bool 类型的变量IsBodyHtml可以设置。是否支持发送HTML内容。

 

另请参阅

Membership.Providers Property









posted @ 2011-11-27 22:00  技术弟弟  阅读(3337)  评论(5编辑  收藏  举报