Custom Authorization in the ASP.NET MVC Framework and Authorize Attribute

Not a day goes by that I don't get all giddy about the extensibility of the ASP.NET MVC Framework. Case in point, authorization in the ASP.NET MVC Framework. At the most basic level we have the AuthorizeAttribute that allows you to secure controller actions. You have the simple case where only an authenticated user can access a controller action:

 

public class ProductsController : Controller

{

    [Authorize]

    public ActionResult Create()

    {

        return View();

    }

}

 

or maybe only users in the Admin Role can access the action, etc:

 

public class ProductsController : Controller

{

    [Authorize(Roles = "Admin")]

    public ActionResult Create()

    {

        return View();

    }

}

 

For simple web applications that might be all you need. Out of the box the AuthorizeAttribute will grab the IPrincipal and check to make sure it has been authenticated and interrogate the username and roles depending on your settings.

However, sometimes your client has a more sophisticated authorization service that does magic behind the scenes as to whether a request is authorized to perform an action. This might seem like a daunting task, but once again the ASP.NET MVC Framework has your back. Let's go ahead and derive a custom attribute from AuthorizeAttribute and have it call an IAuthorizationService that will interface with the client's custom authorization service.

 

public class CustomAuthorizeAttribute : AuthorizeAttribute

{

    public IAuthorizationService _authorizationService { get; set; }

 

    protected override bool AuthorizeCore(HttpContextBase httpContext)

    {

        return _authorizationService.Authorize(httpContext);

    }

}

 

Now I can decorate my controller action methods with the new attribute that uses the IAuthorizationService:

 

[CustomAuthorize]

public ActionResult Create()

{

    return View();

}

 

And that is it. I don't really care what IAuthorizationService does in the background. We have essentially given ourselves a bit more room to grow and change our authorization scheme and that can be a good thing :)

Keep in mind this is just one of several simple ways to do this.

Hope this helps,

 

David Hayden

 

ASP.NET MVC Tutorials

 

posted on Thursday, April 09, 2009 11:33 AM

Main

David Hayden Google +

David Hayden Twitter

Health & Fitness

JavaScript Patterns Book Review

HTML 5 and CSS3 - Develop with Tomorrow's Standards Today

Professional ASP.NET Design Patterns Book Review

Beginning Mac Programming Book Review

C# in Depth Book Review

ASP.NET MVC

Orchard CMS

Categories