Custom Authorize Filter
We've all used the [Authorize]
attribute in ASP.NET MVC applications. To limit access to a particular action to users of two roles, you'd use something like [Authorize(Roles="Admin,Moderator")]
on the action.
There's always a chance that we mistype the role names. So let's refactor the roles into constants:
public static class RoleConstants
{
public const string Admin = "Admin";
public const string Moderator = "Moderator";
// more roles
}
The authorize attribute now becomes: [Authorize(Roles=RoleConstants.Admin+","+RoleConstants.Moderator)]
Now, that's going to be a pain to type for every action you want.
Let's extend the AuthorizeAttribute
class.
Here we go:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public MyAuthorizeAttribute(params string[] roles)
{
Roles = String.Join(",", roles);
}
}
We can now use it as:
[MyAuthorize(RoleConstants.Admin, RoleConstants.Moderator)]
This works on both MVC 5 and .NET Core.
Here's a .NET Core sample repo, in case you're interested.
Update:
If RoleConstants
was an enum, the custom attribute would be something like:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public MyAuthorizeAttribute(params RoleConstants[] roles)
{
// Just do this in a better way
// you don't want to iterate through roles twice
Roles = String.Join(",", roles.Select(r => r.ToString()));
}
}
Easy Peasy!