Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only user permissions in MVC3 application with minimum changes

I've got a task of creating a read-only user for our ASP.Net MVC3 application. I.e. they can login, view all the data, but can not update any data.

I have read a lot of authentication articles/frameworks, like this one: Implement secure ASP.NET MVC applications, or Fluent Security Configuration, or Creating Action Filters in ASP.Net MVC (and a few other, I have lost links to already).

The problem with most of the approaches that they require drastic changes to the domain/application. And I have only one day to implement the feature.

We have about a hundred of controllers with on average of 4 actions per controller (mostly CRUD operations), and going through every single one of them is out of the question. Also it would be easy to forget to put attributes on the the new code - introducing bugs.

So far I have came up with global filter that denies all POST-based actions and controller actions called "Create" for read-only user:

public class ReadOnlyFilter : IActionFilter 
{

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var currentUser = HttpContext.Current.User;
        if (currentUser == null || !currentUser.Identity.IsAuthenticated)
            return; // user is not logged in yet


        if (!currentUser.IsInRole("Readonly")) 
            return; // user is not read-only. Nothing to see here, move on!

        // Presume User is read-only from now on.


        // if action is of type post - deny
        if (filterContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
        {
            filterContext.HttpContext.Response.Redirect("~/ReadOnlyAccess");
        }

        // if action is "Create" - deny access
        if (filterContext.ActionDescriptor.ActionName == "Create")
        {
            filterContext.HttpContext.Response.Redirect("~/ReadOnlyAccess");
        }

        // if action is edit - check if Details action exits -> redirect to it.
        //TODO get this done ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        return;
    }


    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // blah! have to have this here for IActionFilter
    }
}

Next thing I plan to create attribute [AllowReadOnlyUser] for post actions, like changing the password/email, and in the filter allow that action to go through.

I wonder if there are better ways to do this kind of thing?

Update: The application is not for public consumption. It is used in corporate world to track people, assets and other boring data.

Update 2: I've seems to be finished with this task. Done it as a controller, as started. Full code and some explanation you can see in my blog.

like image 612
trailmax Avatar asked Sep 18 '12 10:09

trailmax


2 Answers

you can use the System.Web.Mvc.AuthorizeAttribute for your purpose. Create a class that derives from AuthorizeAttribute and override the methods AuthorizeCore and HandleUnauthorizedRequest. In AuthorizeCore you determine if a user is allowed to execute an action, in HandleUnauthorizedRequest you determine what to display if he isn't allowed (for instance, show a "NotAllowed"-View).

After creating your custom authorization attribute, you have to add the attribute to all controller actions that should be protected by your custom authorization. For instance, all POST-methods. But if there is a POST-method that should be allowed for all users, you just don't add the attribute to that controller action.

like image 101
Dirk Trilsbeek Avatar answered Sep 19 '22 13:09

Dirk Trilsbeek


You'll have to tweak this a bit, and before anyone tells me I am 100% aware that this is a terrible hack. But it's also pretty effective and very quickly implemented which was the overriding concern at the time. You'll want to run this through an obsficator of course.

There is also some update panel stuff in there that would have to be removed, or changed to jQuery ajax response end hooks or something like that if needed.

Oh and there is this to control running it for read only users only:

if (isReadonly && !Page.ClientScript.IsClientScriptBlockRegistered("ReadonlyScriptController"))
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), 
  "ReadonlyScriptController", "<script>RunReadonlyScript();</script>");
}

Script:

<script type="text/javascript" src="<%# Page.ResolveUrl("~/ClientScripts/jquery-1.4.2.min.js") %>"></script>
<script type="text/javascript">
    function RunReadonlyScript() {
        //Extend jquery selections to add some new functionality
        //namely, the ability to select elements based on the
        //text of the element.
        $.expr[':'].textEquals = function (a, i, m) {
            var match = $(a).text().match("^" + m[3] + "$");
            return match && match.length > 0;
        };
        //this function does all the readonly work
        var disableStuff = function () {

            //select all controls that accept input, save changes, open a popup, or change form state
            // ** customize this with your own elements **
            $('button, input:not(:hidden), textarea, select,
              a:textEquals("Clear Selection"), 
              a:textEquals("Add Message"), 
              a:textEquals("CCC EVAL"),
              a[id$="availLink"], 
              a[id$="lbtnDelete"], 
              a[id$="lbtnEdit"]')
                //disable input controls
                .attr('disabled', 'disabled')
                //remove onclick javascript
                .removeAttr('onclick')
                //remove all bound click events
                .unbind("click")
                //add a new click event that does nothing
                //this stops <a> links from working
                .click(function (e) {
                    e.preventDefault(); 
                    return false;
                });

            //zap some images with click events that we don't want enabled
            $('img[id$="imgCalendar1"], img[id$="imgDelete"]').hide();
        }
        //if we are loading the home page, don't disable things
        //or the user won't be able to use the search controls
        var urlParts = document.URL.split('/');
        var last2 = urlParts[urlParts.length - 2] + '/' + urlParts[urlParts.length - 1];
        if (last2 !== 'home/view') {
            //disable everything initially
            disableStuff();
            //setup a timer to re-disable everything once per second
            //some tab panels need this to stay disabled
            setInterval(disableStuff, 1000);
            //some pages re-enable controls after update panels complete
            //make sure to keep them disabled!
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(disableStuff);
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(disableStuff);
        }
    }
</script>
like image 35
asawyer Avatar answered Sep 22 '22 13:09

asawyer