65.9K
CodeProject is changing. Read more.
Home

Field Based Security in ASP.NET MVC 3 for Different Roles

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (6 votes)

Jun 14, 2012

CPOL

1 min read

viewsIcon

28844

MVC3 Role base security.

Introduction

This article will show how we can achieve security for each field of your web form in ASP.NET MVC3 for different roles of users.

Override AuthorizeArrtibute and Add Additional Value in Metadata

In order to provide security for each field in ASP.NET application, we can override the Authorize attribute as follows:

[AttributeAssage(AttributeTarget.Property)]
public Class ReadOnlyAuthorizeAttribute : Attribute, ImetaDataAware
{
   public String Roles {get; set;}
   public bool IsReadOnly
   {
     Get
     {
        If(this.Roles ! = null)
        {
           var roleList = this.Roles.Split(‘,’).Select(o => o.Trim()).ToList();
           return !(roleList.Where(role => HttpContext.Current.User.IsInRole(role)).Count() > 0);
        }
        else
           return true;
     }
   }

 
   Public void OnMetataDataCreated(ModelMetaData metadata)
   {
     Metadata.AdditinalValues[“IsReadOnly”] = this.IsReadOnly;
   }
}

The above code checks the logged in user role that is provided along with property Authorize attribute. And on that basis override Metadata to add additional value IsReadOnly.

Model Changes

In Model apply ReadOnlyAuthorize attribute and apply the roles as shown below:

[ReadOnlyAuthorize(“Admin”)]
public string Name {get; set;}

Because of this attribute IsReadOnly will return true for Admin users. Also it will assign Additional value IsReadOnly as true.

Editor Template

Now create a new editor template for Text (String.ascx) and check where Name is readonly or not as shown below: 

<%
   var attribute = new System.Collection.Generic.Dictionary<String, object()> ;
    var isReadOnly = false;
    if(ViewData.ModelMetaData.additionalValues.ContainsKey(“IsReadOnly”))
    {
      isReadOnly = (bool)ViewData.ModelMetaData.additionalValues[“IsReadOnly”];
    }

    If(ViewData.ModelMetaData.IsReadOnly || isReadOnly)
    {
       attribute.Add(“readonly”,”readonly”);
        attribute.Add(“disabled”,” disabled”);
    }
%>

<%: Html.TextBox(string.Empty, ViewData.TemplateInfo.FormattedModelValue, attribute)%>

View Changes

In view use EditorFor Name field as show:

<%: Html.EditorFor(m => Model.Name) %>

As in Model, Name is string so it will go to above editor template String.ascx. And in template it will check for IsReadOnly value. On that basis it will add readonly and disabled html attribute.

In this way we can make Name field as editable as well as readonly by having ReadOnlyAuthorize attribute with different roles.

Similarly we can have editor templates for different controls like TextBox, DropDown, TextArea etc. And can make that field as readonly or editable depending upon the logged in user roles.