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: 48542
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 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 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

  • with role as Manager
  • with role as Sales Manager
  • 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

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

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

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 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 user as shown in the following image


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



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)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades 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), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

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