Custom Authorization Attribute in .NET Core

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(); // logic } 

I would like (or something similar):

 [AdminOnly] [HttpGet] public async Task<IActionResult> Get() { // logic } 

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?

+5
source share
1 answer

The solution suggested by @JoeAudette seems to be the best option.


Create your own policy in Startup.cs :

 options.AddPolicy("PolicyName", p => { p.RequireAuthenticatedUser(); p.RequireClaim("IsAdmin", true); <- your criteria here (claim type, claim value) ??? p.Build(); }); 


Then just use it as an attribute:

 [Authorize("PolicyName")] 
+6
source

Source: https://habr.com/ru/post/1262477/


All Articles