Role based security in MVC application

As the name says provide users to access pages by there access levels security.

Here we will implement role-based security by Action filters so the question is the what is action filters in MVC if you don’t know about the actions filters so will brief it first.

Action Filters: MVC provides a feature to users to allow the filters when an action will be executing or after an action will be executed.
Action filters have two events:

1.On Action Executing
2.On Action Executed

 

Now come to Role-Based Security:

Step-1: Here we have an example of activity calendar management in HR module, so we want to implement role-based security on it

Example: 

[ValidateRequest(true, UserInterfaceHelper.Add_Edit_ActivityCalender, (int)AccessMode.ViewAccess, (int)RequestMode.GetPost)]
public ActionResult AddEditActivityCalender(int activitycalenderId = 0, int accessMode = 3)
{

try
{
if (activitycalenderId != 0)
{

ViewData[“activitycalenderId”] = activitycalenderId;
ViewData[“accessMode”] = accessMode;
ViewData[“currentDate”] = DateTime.Now.ToString(“dd-MMM-yyyy”);
}
else
{
ViewData[“activitycalenderId”] = 0;
ViewData[“accessMode”] = 0;
ViewData[“currentDate”] = DateTime.Now.ToString(“dd-MMM-yyyy”);
}

}
catch (Exception ex)
{
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex);
}
return View();
}

Here we have an action method AddEditActivityCalender here we have to implement ValidateRequest Filter for implementing Role-Based Security.

Step-2: How ValidateRequest works here

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ValidateRequest : FilterAttribute, IAuthorizationFilter
{
public ValidateRequest();
public ValidateRequest(bool isActive, int userInterfaceId, int accessMode = 3, int requestMode = 1);

public void OnAuthorization(AuthorizationContext filterContext);
}

 

more : www.dotnethub.co.in

10 thoughts on “Role based security in MVC application”

    1. We appreciate your feedback dear,

      Please let us know what is the issue with this post we will improve the quality of our Posts

      Team
      Dotnethub

Leave a Reply

Your email address will not be published. Required fields are marked *