Extending authorization policies
VirtoCommerce supports extension of existing authorization policies that are defined and checked in the Api controllers and other places. This article shows how to use the various techniques to extend exist authorization policies type without direct code modification.
Extending existing authorization policies
Let's say we have this authorization checks in the OrderModule. And we want to extend the default OrderAuthorizationHandler
is associated with this requirement OrderAuthorizationRequirement
that is called during this authorization check with a new policy that will limit the resulting orders by their statuses. To be able create a role that allows for concrete users see orders only with specific state(s).
You can read more about how the authorization policies work by this link Policy-based authorization in ASP.NET Core
OrderModuleController.cs
[HttpPost]
[Route("api/order/customerOrders/search")]
public async Task<ActionResult<CustomerOrderSearchResult>> SearchCustomerOrder([FromBody] CustomerOrderSearchCriteria criteria)
{
var authorizationResult = await _authorizationService.AuthorizeAsync(User, criteria, new OrderAuthorizationRequirement(ModuleConstants.Security.Permissions.Read));
if (!authorizationResult.Succeeded)
{
return Unauthorized();
}
}
CustomOrderAuthorizationHandler
class and use the same requirement OrderAuthorizationRequirement
as it used in the original controller method for authorization check.
CustomOrderAuthorizationHandler.cs
public sealed class CustomOrderAuthorizationHandler : PermissionAuthorizationHandlerBase<OrderAuthorizationRequirement>
{
//Code skipped for better clarity
}
OrderAuthorizationRequirement
requirement.
Module.cs
public class Module : IModule
{
public void Initialize(IServiceCollection serviceCollection)
{
//Rest of code skipped for better clarity
serviceCollection.AddTransient<IAuthorizationHandler, CustomOrderAuthorizationHandler>();
}
}
CustomOrderAuthorizationHandler
along with another registered handlers will be executed each time when OrderAuthorizationRequirement
being checked by this call
IAuthorizationService.AuthorizeAsync(User, data, new OrderAuthorizationRequirement());