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:

1public static class RoleConstants
2{
3    public const string Admin = "Admin";
4    public const string Moderator = "Moderator";
5    // more roles
6}

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:

1public class MyAuthorizeAttribute : AuthorizeAttribute
2{
3    public MyAuthorizeAttribute(params string[] roles)
4    {
5        Roles = String.Join(",", roles);
6    }
7}

We can now use it as:

1[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:

1public class MyAuthorizeAttribute : AuthorizeAttribute
2{
3    public MyAuthorizeAttribute(params RoleConstants[] roles)
4    {
5        // Just do this in a better way
6        // you don't want to iterate through roles twice
7        Roles = String.Join(",", roles.Select(r => r.ToString()));
8    }
9}

Easy Peasy!

<< Previous Post

|

Next Post >>

#.NET