MVC configure value Authorize roles and strongly typed role

To authorize a controller for a specific role, the following attribute is required in the controller class:

[Authorize(Roles = "SampleRole")] 

This requires the role name to be hardcoded on the controller and does not seem to be a flexible solution. My question is that you can specify a value for this role in the web.config file and use this key in the controller?

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

And in the controller

 [Authorize(Roles = "SampleRoleKey")] 

Another question: can we use a strongly typed role to authorize the controller?

+4
source share
1 answer

Use a static class with public const-s:

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

Create your own MyAuthorizeAttribute attribute, obtained from AuthorizeAttribute, to have a property that can handle an array of strings, and then:

 [MyAuthorize(MyRoles = new[]{ Roles.SampleRoleKey }] 
+4
source

All Articles