Creating a Filter for Custom Roles in .NET Core 2

by John Kuefler • January 8, 2018

Extending .Net Core 2 identity

The role system built into newly created .Net Core 2 MVC apps when you select the “Individual User Accounts” option works great for most scenarios. However, there may be times when you need to pull roles in another fashion to meet your business need. Thankfully, it’s easy to hook up a helper that makes it trivial to guard controller actions based on role. The goal is to be able to do something like this:

With a filter like this, we can only allow people in one or more of the named roles to access this controller action.

To start you’ll need to create a new filter. I put this one in a file called “CustomAuth.cs” in the root of the project. Inside of here, we need to add two classes – one inheriting TypeFilterAttribute that we will place above our controller actions, and another implementing IAuthorization filter that checks the source of truth for our roles. They look like this:

That’s it! This provides a simple way to easily use your own roles if you need to lock down controller actions and can’t utilize the built in .net identity stuff.

Are you using the right password manager for your agency?

ElePass is a password management solution built for agencies – developed by DevSquared. With security as the backbone, we built ElePass to drive agencies towards a more secure environment and to ensure your clients can trust you with their accounts. Check out some of the features of ElePass and give it a try today!