技术开发 频道

ASP.NET MVC3:用密码保护限制view访问

   将来用户再次访问网站的时候,如果FormsAuthentication cookie仍然被保存(假设在登录的时候他选定了记住我选项,或者他没有关闭浏览器),他们就不需要再次登录。

  如果cookie没有被保存。他就要被导航到登录页面了。一旦用户输入了登陆信息并且提交表单。AccountController将再通过Membership 类去验证用户。如下:

[HttpPost]
public ActionResult LogOn(LogOnModel 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);
}

  上边的代码页是自动生成的。做了三件事:

  ①通过 Membership.ValidateUser() 验证用户名和密码

  ②如果登陆成功,使用FormsAuthentication.SetAuthCookie 来保存一个cookie。

  ③如果通过验证,会导航到主页,否则会在登陆页显示错误信息。

  AuthorizeAttribute 特性可以进一步限定特定的用户组或者特定的用户才可以访问指定的action

  例如:

// Retrieve a list of all users to allow an admin
// to manage them
[Authorize(Roles = "Admin")]
public ActionResult UserAdmin()
{
MembershipUserCollection users =
Membership.GetAllUsers();
return View(users);
}
// Create some custom reports for me only
[Authorize(Users = "Jamie")]
public ActionResult JamieAdmin()
{
// Perform some logic to generate usage reports
...
return View();
}
0
相关文章