我已经设置了一个存储库类来获取用户对象,并检查输入的密码是否与从数据库检索到的密码匹配。当然,密码是通过一些额外的安全措施进行哈希处理的。
不过,我一直在网络上进行一些研究,但我仍然有点困惑如何在用户登录后对用户进行身份验证。我知道每个用户都有一个 [Authorize]
标签 Controller /操作方法基本上意味着:仅允许当前用户在经过身份验证后访问此页面。
我只是无法理解如何验证它们。
这就是我现在所处的位置:
if (hashedPassword == user.Password)
{
//Correct Login Details
//Mark this user as Authenticated/Logged in
}
我正在使用 ASP.NET MVC 4、C#。
感谢您提供任何提示、技巧和答案。
最佳答案
这很大程度上取决于您使用的身份验证框架。
使用WebSecurity
的方法之一是
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
如果您使用 SimpleMembership 提供程序,则可以使用:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && membershipProvider.Login(model.UserName, model.Password, model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
或者对于较旧的成员(member)提供商,这有效:
[HttpPost]
public virtual ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
关于c# - 在登录 ASP.NET MVC 时验证用户身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20830604/