Skip to content
Last update: August 24, 2024

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.

Sample code

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).

Readmore Authorization policies

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();
    }
}

To implement this extension:

  1. Define a new authorization handler. Create a new class named CustomOrderAuthorizationHandler and utilize the existing OrderAuthorizationRequirement requirement for authorization checks:

    CustomOrderAuthorizationHandler.cs
    public sealed class CustomOrderAuthorizationHandler : PermissionAuthorizationHandlerBase<OrderAuthorizationRequirement>
    {
        // Implementation details omitted for clarity
    }
    
  2. 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:

    Module.cs
    public class Module : IModule
    {
        public void Initialize(IServiceCollection serviceCollection)
        {
            // Other code omitted for clarity 
            serviceCollection.AddTransient<IAuthorizationHandler, CustomOrderAuthorizationHandler>();
        }
    }
    
  3. Execute authorization checks. The custom CustomOrderAuthorizationHandler, along with other registered handlers, will execute each time an OrderAuthorizationRequirement is checked, as demonstrated in the following code snippet:

    IAuthorizationService.AuthorizeAsync(User, data, new OrderAuthorizationRequirement());
    

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.

Readmore Handling secure web API