I am creating an API in .NET Core 1.1. I create a User object from HttpContext.User in the base controller, to which all my other controllers are inherited, and authentication is enabled by default (if necessary, it must be disabled manually using [AllowAnonymous] ). The User object has the IsAdmin property. I am now checking to see if the user is the administrator at the top of each relevant function, as shown below, but I feel that there should be a way to add a custom attribute to simplify and clean this code.
For reference, User.IsAdmin is an abbreviation for this:
bool.Parse(HttpContext.User.FindFirst("IsAdmin")?.Value)
Instead of this:
[HttpGet] public async Task<IActionResult> Get() { if (!User.IsAdmin) return Forbid();
I would like (or something similar):
[AdminOnly] [HttpGet] public async Task<IActionResult> Get() {
I tried looking at the source for [AuthorizeAttribute] to try to build, but it's just a wrapper, and I don't know where the real magic happens.
How can i do this?
source share