DotNetCurry Logo

Access same Action Method by Multiple Roles in ASP.NET MVC using Configuration File

Posted by: Mahesh Sabnis , on 3/29/2016, in Category ASP.NET MVC
Views: 16834
Abstract: Defining Multi-Roles Access for Action Methods in ASP.NET MVC using Configuration File

One prominent feature of the ASP.NET MVC platform is the ease with which you can implement security for controlling application access for users and/or roles. The implementation of the Role Based Security in ASP.NET MVC 5 is already published here http://www.dotnetcurry.com/aspnet-mvc/1102/aspnet-mvc-role-based-security. This article explains how to use ASP.NET Identity and the IdentityRole class for creating and managing roles. The Article also creates a custom AuthorizeAttribute class for providing Authorization based on user roles.

 

In MVC, we can control the access of an action method from the controller using the Authorize attribute. This is an action filter class that provides Users and Roles properties. These properties can contain comma (,) separated Users or Roles and hence we can access an action method for multiple users or roles. One approach is to hard-code users and roles names, which might not be the good idea during production. We need to use a technique using which if Roles are created dynamically by the Administrator, then they should be configurable for the application. We can implement this by using the Web.config file.

Accessing Action Method by multiple users and roles - The Implementation

To implement this application, please visit the code for Role Based Security from this link http://www.dotnetcurry.com/aspnet-mvc/1102/aspnet-mvc-role-based-security. Download the application and extract it. Open the project in Visual Studio 2013/2015. The App_Data folder contains SuperMarket.mdf. This is the application database which contains the ProductMaster table. The script for the table is as shown here:

CREATE TABLE [dbo].[ProductMaster](
    [ProductId] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [varchar](50) NOT NULL,
    [Price] [varchar](50) NOT NULL)

The code contains RoleController which contains code for creating Roles. The Roles sub-folder of the Views folder contains views for creating and displaying all roles.

The AccountController contains code for creating users. In the AccountController, the Register method for HttpPost contains the following line to assign roles to the user.

await this.UserManager.AddToRoleAsync(user.Id, model.Name);

Step 1: Run the application and create following roles

  • Manager
  • Sales Executive
  • Sales Manager

Step 2: Create the following users using Register View

  • manager@mssales.com with role as Manager
  • salesmanager@mssales.com with role as Sales Manager
  • salesexecutive@mssales.com with role as Sales Executive

Step 3: Open the ProductController class. This class contains Create and SaleProduct action methods. These methods are applied by the AuthLog attribute having the Role property value as Manager and Sales Executive respectively. This means that only users of respective roles will be able to access these methods. Our requirement in this case is that we want the SaleProduct method to be accessed by Sales Executive and Sales Manager roles, but at the same time we do not want to hard-code these values in the AuthLog attribute. So to implement this, we will follow the steps shown next.

 

Step 4: Open the Web.config file and add the following custom section in the configSections.

<section name="AppRoles" type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

And add the custom tag as shown in the following code

<AppRoles>
    <add key="AppPermissions" value="Sales Executive,Sales Manager" />
</AppRoles>

The above tag defines the AppPermission key with value as Sales Executive and Sales Manager. Note that since this is a configuration file, we can dynamically keep on adding values for AppPermission.

Step 5: In the CustomFilters folder, we have the LogAuthFilter.cs code file which contains the AuthLogAttribute class. This class is derived from AuthorizeAttribute class. This contains logic for Role based Security. Modify the constructor code as shown in the following code:

public AuthLogAttribute(params string[] roleIds)
{
    var appRoles = new List<string>();
    var roleList = (NameValueCollection)ConfigurationManager.GetSection("AppRoles");
    foreach (var roleId in roleIds)
    {
        appRoles.AddRange(roleList[roleId].Split(new[] { ',' }));
    }
    Roles = string.Join(",", appRoles);
    View = "AuthorizeFailed";
}

The constructor accepts the params array of name roleIds. The local variable roleList, will be used to store all name value collections from the AppRoles section created in Web.config file as discussed in Step 4. We move ahead by iterating through the roleIds, which will be applied on the action method of the controller using the key of the custom tag declared in the Web.config file. This will contains list of all roles. The code will store all roles in the Role property.

Step 6: Modify the AuthLog attribute value on the SaleProduct action method as shown in the following code

[AuthLog("AppPermissions")]
public ActionResult SaleProduct()
{
    ViewBag.Message = "This View is designed for the Sales Executive and Sales Manager to Sale Product.";
    return View();
}

The AuthLog accepts the AppPermissions as a parameter. This is passed to the constructor of the AuthLogAttribute class. The code in the constructor will read the values defined for the AppPermission key from the web.config file which is Sales Executive and Sales Manager. This means the SaleProduct can now be accessed by users in these roles.

Run the application and login with salesmanager@mssales.com and call the SaleProduct method (Click on the Sale Product link of the navigation bar at the top of the page.) The Sale Product view will be displayed with salesmanager@mssales.com user as shown in the following image

mvc-user-access

Now Log off and login with the salesexecutive@mssales.com and click on Sale Product link, the action method will be executed for this user too.

mvc-role-access

Conclusion:

In an ASP.NET MVC application, we can access the same action method for multiple user roles by defining them in a configuration file dynamically.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!