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)].
Of course you'd want to rename MyAuthorize to something else.

This works on both MVC 5 and .NET Core.
Here's a .NET Core sample repo, in case you're interested.

Galdin Raphael

Galdin Raphael is an independent full stack developer from Mumbai.

Subscribe to Galdin's Blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!