Let's say that you have a .net web api with a GetResource(int resourceId) action. This action (with the specified id) should only be authorized for a user associated with that id (the resource could for instance be a blogpost written by the user).
This could be solved in many ways, but an example is given below.
public Resource GetResource(int id)
{
string name = Thread.CurrentPrincipal.Identity.Name;
var user = userRepository.SingleOrDefault(x => x.UserName == name);
var resource = resourceRepository.Find(id);
if (resource.UserId != user.UserId)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
return resource;
}
where the user has been authenticated by some sort of mechanicm.
Now, let's say that I also want a user of, for instance, an admin type, to be authorized to consume the endpoint (with the same id). This user does not have any direct relation to the resource but does have authorization because of it's type (or role). This could be solved by just checking if the user is of admin type and the return the resource.
Is there any way to centralize this in a way so that I don't have to write authorization code in every action?
Edit Based on the answers I think I have to clarify my question.
What I am really after is some mechanism that makes it possible to have resource based authorization, but at the same time allow some users to also consume the same endpoint and the same resource. The action below would solve this for this specific endpoint and for this specific Role (Admin).
public Resource GetResource(int id)
{
string name = Thread.CurrentPrincipal.Identity.Name;
var user = userRepository.SingleOrDefault(x => x.UserName == name);
var resource = resourceRepository.Find(id);
if (!user.Roles.Any(x => x.RoleName == "Admin" || resource.UserId != user.UserId)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
return resource;
}
The thing I am after is some generic way to solve this problem so that I don't have to write two different endpoints with the same purpose or write resource specific code in every endpoint.
Very easy
Requirement
public class PrivateProfileRequirement : IAuthorizationRequirement
{
public string ClaimType { get; }
public PrivateProfileRequirement(string claimType)
{
ClaimType = claimType;
}
}
public class PrivateProfileHandler : AuthorizationHandler<PrivateProfileRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PrivateProfileRequirement requirement)
{
if (context.User != null)
{
if (context.User.Claims.Any(c => string.Equals(c.Type, requirement.ClaimType, StringComparison.OrdinalIgnoreCase)))
{
if (context.User.Identities.Any(i => string.Equals(i.GetId(), context.Resource)))
{
context.Succeed(requirement);
}
}
}
return Task.CompletedTask;
}
}
Startup.cs
services.AddAuthorization(options =>
{
options.AddPolicy("PrivateProfileRequirement",
policy => policy
.RequireAuthenticatedUser()
.RequireRole(Role.Profile.ToRole())
.AddRequirements(new PrivateProfileRequirement(ClaimTypes.NameIdentifier)));
});
Controller
public class ProfileController : Controller
{
private readonly IAuthorizationService _authorizationService;
public ProfileController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
}
Action
public async Task<IActionResult> OnGetAsync(int id)
{
var profile = _profileRepository.Find(id);
if (profile == null)
{
return new NotFoundResult();
}
var authorizationResult = await _authorizationService
.AuthorizeAsync(User, profile.Id, "PrivateProfileRequirement");
if (authorizationResult.Succeeded)
{
return View();
}
return new ChallengeResult();
}
For resource based authorization, I'd suggest to use claim based identity and embed user id as a claim. Write an extension method to read the claim from identity. So the sample code will look like:
public Resource GetResource(int id)
{
var resource = resourceRepository.Find(id);
if (resource.UserId != User.Identity.GetUserId())
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
return resource;
}
If you want to simplify the code further more, you may write a UserRepository which knows user data and resource repository to centralize the code. The code will look like:
public Resource GetResource(int id)
{
return User.Identity.GetUserRepository().FindResource(id);
}
For role based authorization, AuthorizeAttribute will be the best place to handle it and you'd better use separate action or controller for that.
[Authorize(Roles = "admin")]
public Resource GetResourceByAdmin(int id)
{
return resourceRepository.Find(id);
}
[Edit] If OP do want to use one single action to handle different types of users, I personally prefer to use a user repository factory. The action code will be:
public Resource GetResource(int id)
{
return User.GetUserRepository().FindResource(id);
}
The extension method will be:
public static IUserRepository GetUserRepository(this IPrincipal principal)
{
var resourceRepository = new ResourceRepository();
bool isAdmin = principal.IsInRole("Admin");
if (isAdmin)
{
return new AdminRespository(resourceRepository);
}
else
{
return new UserRepository(principal.Identity, resourceRepository);
}
}
The reason that I don't want to use AuthorizeAttribute to do per resource authentication is that different resources may have different code to check ownership, it's hard to centralized the code in one attribute and it requires extra DB operations which is not really necessary. Another concern is that AuthroizeAttribute happens before parameter binding, so you need to make sure the parameter of the action is coming from route data. Otherwise, for example, from a post body, you won't be able to get the parameter value.
I would look at implementing a custom System.Web.Http.AuthorizeAttribute which you could apply to actions that need this specific authorization rule. In the custom Authorization you can allow access if the user is a member of the Admins group, or if they are the author of the resource.
EDIT:
Based on OP's edit, allow me to expand what I was saying. If you override AuthorizeAttribute, you can add logic like:
public class AuthorizeAdminsAndAuthors : System.Web.Http.AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
return currentUser.IsInRole("Admins") || IsCurrentUserAuthorOfPost(actionContext);
}
private bool IsCurrentUserAuthorOfPost(HttpActionContext actionContext)
{
// Get id for resource from actionContext
// look up if user is author of this post
return true;
}
This is pseudo-code, but should convey the idea. If you have a single AuthorizeAttribute that determines authorization based on your requirements: Current request is either from the author of the post or an Admin then you can apply AuthorizeAdminsAndAuthors Attribute to any resource where you require this level of authorization. So your resource would look like:
[AuthorizeAdminsAndAuthors]
public Resource GetResource(int id)
{
var resource = resourceRepository.Find(id);
return resource;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With