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();
}
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.
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.
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
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With