I'm building an API in .NET Core 1.1. I build a custom User
object from HttpContext.User
in a base controller that all of my other controllers inherit from, and I have authentication enabled by default (must be manually disabled with [AllowAnonymous]
when necessary). The User
object has an IsAdmin
property. Right now I'm checking if the user is an admin at the top of each relevant function like below, but I feel like there must be a way to add a custom attribute to simplify and clean up this code.
For reference, User.IsAdmin
is shorthand for this:
bool.Parse(HttpContext.User.FindFirst("IsAdmin")?.Value)
Instead of this:
[HttpGet]
public async Task<IActionResult> Get()
{
if (!User.IsAdmin)
return Forbid();
// logic
}
I'd like this (or something similar):
[AdminOnly]
[HttpGet]
public async Task<IActionResult> Get()
{
// logic
}
I tried looking at the source for [AuthorizeAttribute]
to try to build from, but it's just a shell and I don't know where the real magic happens.
How can I accomplish this?