I would like to add Authorization to a controller, for multiple Roles at once.
Normally that would look like this:
[Authorize(Roles = "RoleA,RoleB,RoleC")] public async Task<ActionResult> Index() { }
But I have stored my Roles in consts, since they might change or be extended at some point.
public const RoleA = "RoleA"; public const RoleB = "RoleB"; public const RoleC = "RoleC";
I cannot do this, since the string must be known at compile time:
[Authorize(Roles = string.join(",",RoleA,RoleB,RoleC)] public async Task<ActionResult> Index() { }
Is there a way to circumvent the problem?
I COULD write a const which simply contains "RoleA,RoleB,RoleC" - but I dislike magic strings and this is a magic string. Changing the name of a Role and forgetting to change the combined string would be a disaster.
I am using MVC5. ASP.NET Identity and the Role are known at compile time.
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. Right-click on the Models folder and add a database model.
If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.
You can place the Authorize attribute on a controller or on individual actions inside the controller. When we place the Authorize attribute on the controller itself, the authorize attribute applies to all of the actions inside.
Try to create custom authorize attribute like this.
public class AuthorizeRolesAttribute : AuthorizeAttribute { public AuthorizeRolesAttribute(params string[] roles) : base() { Roles = string.Join(",", roles); } }
Assuming your roles will be the same for multiple controllers, create a helper class:
public static class Role { public const string Administrator = "Administrator"; public const string Assistant = "Assistant"; }
Then use it like so:
public class MyController : Controller { [AuthorizeRoles(Role.Administrator, Role.Assistant)] public ActionResult AdminOrAssistant() { return View(); } }
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