Making sure a user is logged in to gain access to a view
The easiest way to accomplish this is to use the Authorize attribute above a controller's action method. For instance, we only want to allow users to change thier password if they are already logged into the site. In order to prevent non-authorized users from reaching the change password view we can restrict access like this:
[Authorize]
public ActionResult ChangePassword()
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View();
}
You can also accomplish this manually by checking against the User object like this:
public ActionResult ChangePassword()
{
if (!User.Identity.IsAuthenticated)
return RedirectToAction("LogOn", "Account");
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View();
}
Making sure a user is in a particular role to gain access to a view
You may have some views which should only be accessable to users of a particular role. This can also be accomplished using the Authorize attribute like this:
[Authorize(Roles = "Administrator")]
public ActionResult Index()
{
return View();
}
You can accomplish this in code as well using the following method:
public ActionResult Index()
{
if (!User.IsInRole("Administrator"))
return RedirectToAction("LogOn", "Account");
return View();
}
reference: Using our Role and Membership Providers