Skip to main content
Post Closed as "Not suitable for this site" by t3chb0t, pacmaninbw, dfhwze, Toby Speight, Grajdeanu Alex
Tweeted twitter.com/StackCodeReview/status/1172842532344074242
edited tags
Link
dfhwze
  • 14.2k
  • 3
  • 40
  • 101
Source Link
Matt G
  • 129
  • 2

ASP.Net Core WebAPI Authorization Policy for User or Admin

I have a controller that returns data about users. I want to set the authorization such that an admin can access this controller and retrieve data for any user, and a non-admin user can access the controller and retrieve data for themselves.

I've ruled out using [Authorize (Roles = "Admin")] because this means users can't get their own data. So I've inserted the following logic into the controller action:

var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;
var roles = _httpContextAccessor.HttpContext.User.FindAll(ClaimTypes.Role);

var query = roles.Select(r => r.Value).Contains("Admin");

Customer customer =await _context.Customers.FindAsync(id);

if (!(customer.EmailAddress == userId || query))
 return Unauthorized();

This is roughly equivalent to this Stack Overflow answer, but for ASP.Net Core rather than MVC.

My question is, is there a way to do this with an Authorization Policy? Adding the RequireRole check is straightforward and covered in the MS Documentation as well as countless blogs, but I couldn't find or figure out a way to use a policy to check that the data the user is trying to access is their own.

I'm sure this isn't an uncommon requirement, is there a way to do this, or is what I'm currently doing OK? The only other approach I could think of was to have two separate endpoints, but both options seem inelegant.