只是想知道在mvc3中处理登录/用户身份验证的最佳做法是什么。最好使用内置成员资格,例如:
[HttpPost]
public ActionResult Register(RegisterUser model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index","User");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
return View(model);
}
或更简单和自定义的东西,例如制作自己的cookie以避免每次都必须使用预先打包的数据库结构?
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(10),
false,
null);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
this.Response.Cookies.Add(cookie);
答案 0 :(得分:3)
我个人同意Stack Overflow采用两种方式直接通过Stack Exchange和OpenId / OAuth访问进行注册的方法;谷歌,雅虎,Facebook,Twitter等
在提供您自己的注册时,我会坚持使用ASP.NET成员资格提供程序或通过NuGet提供的类似服务提供程序。
使用OpenId和OAuth时,DotNetOpenAuth取得了巨大成功。请参阅Andrew Arnott详细解答使用OpenId的好处和理由:To OpenID or not to OpenID? Is it worth it?
答案 1 :(得分:2)
出于某种原因存在ASP.NET成员资格。
如果它像设置cookie一样简单,LinkedIn黑客就没有我的密码。
答案 2 :(得分:1)
我建议您最好的选择是提供自定义提供程序,这样您就不必使用“预打包”数据库。通过这种方式,您可以重复使用内置的身份验证和授权,同时仍然拥有自定义的用户数据库。
这并不困难,只需创建一个派生自MembershipProvider
的类(如果要包含角色,则为RoleProvider
)。这些是抽象类,因此您需要提供各种方法的实现。为了节省必须为所有方法提供实现,您可以使用不使用的方法抛出NotImplementedException
。