Question

In order to authorize a controller for a particular role, following attribute is required on the controller class:

[Authorize(Roles = "SampleRole")]

This requires role name to be hard-coded on the Controller and does not seem to be a flexible solution. My question is that, it is possible to specify value for that role in the web.config and using that key in the controller?

<appSettings>
    <add key="SampleRoleKey" value="SampleRole" /> 
    ...
</appSettings>

And in the controller,

[Authorize(Roles = "SampleRoleKey")]

Another question is that, can we use strongly typed role to authorize the controller?

Was it helpful?

Solution

Use a static class with public const-s:

public static class Roles
{
    public const string SampleRoleKey = "SampleRole";
}

Create a custom MyAuthorizeAttribute derived from AuthorizeAttribute to have a property which can handle an array of strings and then:

[MyAuthorize(MyRoles = new[]{ Roles.SampleRoleKey }]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top