The whole advantage with MVC over webforms is extensibility at every point. Extensibility, Extensibility, Extensibility.
Authorization is a very important and every web project has there own needs and requirements. Full customisation is paramount.
Here I will show you a simple way to customise your authorization.
In MVC attributes are used to protect a controller method, so we to get started all we need to do is inherit from the AuthorizeAttribute class.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string[] users = Users.Split(',');
if (!httpContext.User.Identity.IsAuthenticated)
return false;
if (users.Length > 0 &&
!users.Contains(httpContext.User.Identity.Name,
StringComparer.OrdinalIgnoreCase))
return false;
return true;
}
}
This is the basics. We can put any logic we like in here and all we have to do is return false if for whatever reason the user should not be authorized. Then all you need to do is decorate the controller method with the new attribute as below.
[CustomAuthorize]
public ActionResult Index()
{
return View();
}
From this simple example we can expand it with custom Roles.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// the "new" must be used here because we are hiding
// the Roles property on the underlying class
public new SiteRoles Roles;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
string[] users = Users.Split(',');
if (!httpContext.User.Identity.IsAuthenticated)
return false;
SiteRoles role = (SiteRoles)httpContext.Session["role"];
if (Roles != 0 && ((Roles & role) != role))
return false;
return true;
}
}
Where the SiteRoles class is defined as below.
[Serializable]
[Flags]
public enum SiteRoles
{
User = 1 << 0,
Admin = 1 << 1,
Helpdesk = 1 << 2
}
This can then be used be used as follows.
[CustomAuthorize(Roles=SiteRoles.Admin|SiteRoles.HelpDesk)]
public ActionResult Index()
{
return View();
}
This will only allow the Admin and the Helpdesk Role access to the Index controller. If you don’t belong to one of these roles then you will be sent to the Login page.
The possibilities are really endless.
Happy coding.