ASP.NET MVC2 Access-Control: How to do authorization dynamically?

Posted by Shaharyar on Stack Overflow See other posts from Stack Overflow or by Shaharyar
Published on 2010-06-02T13:54:48Z Indexed on 2010/06/02 14:53 UTC
Read the original article Hit count: 781

We're currently rewriting our organizations ASP.NET MVC application which has been written twice already. (Once MVC1, once MVC2). (Thank god it wasn't production ready and too mature back then).

This time, anyhow, it's going to be the real deal because we'll be implementing more and more features as time passes and the testruns with MVC1 and MVC2 showed that we're ready to upscale.

Until now we were using Controller and Action authorization with AuthorizeAttribute's.

But that won't do it any longer because our views are supposed to show different results based on the logged in user.

Use Case: Let's say you're a major of a city and you login to a federal managed software and you can only access and edit the citizens in your city.

Where you are allowed to access those citizens via an entry in a specialized MajorHasRightsForCity table containing a MajorId and a CityId.

What I thought of is something like this:

Public ViewResult Edit(int cityId) {
    if(Access.UserCanEditCity(currentUser, cityId) {
        var currentCity = Db.Cities.Single(c => c.id == cityId);
        Return View(currentCity);
    } else {
        TempData["ErrorMessage"] = "Yo are not awesome enough to edit that shizzle!"
        Return View();
    }

The static class Access would do all kinds of checks and return either true or false from it's methods.

This implies that I would need to change and edit all of my controllers every time I change something. (Which would be a pain, because all unit tests would need to be adjusted every time something changes..)

Is doing something like that even allowed?

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc-2