When you only have one login page, then it's easy to add the authorize attribute to your action and you'll automatically be directed to the login page in your web.config
[Authorize(Roles = "Administrator")]
public ActionResult EditCategory(int id)
{
return View();
}
On my sites, I have a separate login page for the Administrative area, so I needed to create a custom attribute.
[CustomAuthorization(LoginPage = "~/Admin/LogOn", Role = "Administrator")]
public ActionResult EditCategory(int id)
{
return View();
}
/// <summary>
/// Allows you to specify the Login Page and Role with an attribute: [CustomAuthorization(LoginPage="~/Admin/LogOn",Role="Administrator")]
/// </summary>
/// <param name="filterContext"></param>
public class CustomAuthorization : AuthorizeAttribute
{
public string LoginPage { get; set; }
public string Role { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
//Send the return url to the login page
LoginPage += "?ReturnUrl=" + filterContext.HttpContext.Request.RawUrl;
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.HttpContext.Response.Redirect(LoginPage);
}
else
{
if (Role != null)
{
if(!filterContext.HttpContext.User.IsInRole(Role))
filterContext.HttpContext.Response.Redirect(LoginPage);
}
}
base.OnAuthorization(filterContext);
}
}
No comments:
Post a Comment