Authorization Policies Extension¶
Virto Commerce supports extendng the existing authorization policies that are defined and checked in the API controllers and other locations. This article will tell you how to use various techniques to extend the authorization policy type without direct code modification.
Extend existing authorization policies¶
Suppose you have authorization checks in the Order Module, and you want to enhance the default OrderAuthorizationHandler
associated with the OrderAuthorizationRequirement
. This extension aims to introduce a new policy that restricts orders based on their statuses, allowing certain users to view orders only with specific status(es).
[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();
}
}
To implement this extension:
-
Define a new authorization handler. Create a new class named
CustomOrderAuthorizationHandler
and utilize the existingOrderAuthorizationRequirement
requirement for authorization checks: -
Register the custom authorization handler in the Dependency Injection (DI) container to instruct ASP.NET Authorization to invoke it along with other handlers associated with the
OrderAuthorizationRequirement
requirement: -
Execute authorization checks. The custom
CustomOrderAuthorizationHandler
, along with other registered handlers, will execute each time anOrderAuthorizationRequirement
is checked, as demonstrated in the following code snippet:
Following these steps enables you to extend the existing authorization policies within the Order Module, allowing for more fine-grained control over order access based on their statuses.