Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Problem setting the Authorize attribute Role from a variable, requires const

I am having a problem setting the Authorize attribute Role value from a variable. The error message says it requires a const variable. When I create a const type variable it works fine but I am trying to load the value from the Web.Config file or anything else that will allow the end user to set this. I'm using integrated Windows authentication since this is an intranet only application.

Is there a way to check the users role from a controller? I will use this in an if statement to authenticate instead of an attribute.

[Authorize(Roles = Config.GMPUser)]
public ActionResult Index()
   {
      return View();
   }
like image 319
tsquillario Avatar asked Dec 18 '08 01:12

tsquillario


People also ask

How do I set an authorized role in MVC?

Create the following database data tables. Open Visual Studio 2015 or an editor of your choice and create a new project. Choose "web application" project and give an appropriate name to your project. Select "empty" template, check on the MVC box, and click OK.

How can use Authorize attribute in ASP.NET MVC?

Here's how to use the Authorize attribute. You can apply the Authorize attribute to individual methods as well as the controller class as a whole. If you add the Authorize attribute to the controller class, then any action methods on the controller will be only available to authenticated users.


1 Answers

I have a class called StringResources that provides access to static string values. I ran into the same snag and solved the problem in the following manner. I inherited from the AuthorizeAttribute class and added a method override for the AuthorizeCore method. The functionality of the method had a call to IsInRole() and passes in the static string property. That did the trick. The only problem is having to create separate classes for each role (or for combinations of roles in whatever manner your business logic dictates).

public class SystemAdministratorAuthorizationRequiredAttribute
        : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(System.Security.Principal.IPrincipal user)
        {
            return
                user.IsInRole(
                StringResources.AdministrationViewsStrings.SystemAdministratorRoleName
                );
        }
    }
like image 116
brady gaster Avatar answered Oct 05 '22 22:10

brady gaster