Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorize Roles MVC web from web.config

I got the below compilation error when I added "System.Configuration.ConfigurationManager.AppSettings["ADGroupReader"].ToString()" to the authorize role section header.

In the web.config I have: add key="ADGroupReader" value="Readers DEV"

Compilation error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

[AuthorizedRedirect]
[Authorize(Roles = System.Configuration.ConfigurationManager.AppSettings["ADGroupReader"].ToString())]    
public class HomeController : Controller
{
    .....
}

I do not want to hard code the role (Roles="Readers DEV"); I would like to read it from the web.config. How can I do that?

like image 997
ibrahim Avatar asked Apr 20 '17 01:04

ibrahim


People also ask

How do you do role based authorization?

For role-based authorization, the customer is responsible for providing the user ID, any optional attributes, and all mandatory user attributes necessary to define the user to Payment Feature Services. The customer must also define the roles that are assigned to the user.


1 Answers

This attributes tutorial explains attribute parameter restrictions:

Attribute parameters are restricted to constant values of the following types:

  • Simple types (bool, byte, char, short, int, long, float, and double)
  • string
  • System.Type
  • enums
  • object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)
  • One-dimensional arrays of any of the above types

From description above, this assignment is invalid due to existence of ToString method:

[Authorize(Roles = System.Configuration.ConfigurationManager.AppSettings["ADGroupReader"].ToString())]

As a workaround, you can create a custom AuthorizeAttribute with predefined Roles parameter which contains default assignment to Roles with your AppSettings:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public CustomAuthorizeAttribute() 
    {
        this.Roles = ConfigurationManager.AppSettings["ADGroupReader"].ToString();
    }

    // other stuff
}

Usage in controller class:

[AuthorizedRedirect]
[CustomAuthorize]
public class HomeController : Controller
{
    .....
}
like image 134
Tetsuya Yamamoto Avatar answered Sep 22 '22 19:09

Tetsuya Yamamoto