I have a controller that returns data on users. I want to set the authorization so that an administrator can access this controller and retrieve data for any user, and that a non-administrator user can access the controller and retrieve data for himself.
I have excluded to use
(Authorize (Roles = "Admin")) because it means that users can not get their own data. I've therefore inserted the following logic in 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 response, but for ASP.Net Core rather than MVC.
My question is: is there a way to do that with an authorization policy? The addition of the RequireRole verification is simple and is covered in Microsoft's documentation as well as in countless blogs, but I have not found nor found a way to use a strategy for verify that the data that the user is trying to access is theirs.
I'm sure this is not a rare requirement, is there a way to do that, or is what I'm doing right now? The only other approach I could think of was to have two separate endpoints, but both options seem inelegant.