Hello Magento Friends,
In today’s blog, we will learn about, How to Secure API Endpoints with Custom ACL Resources in Magento 2.
Contents
What are ACL Resources in Magento 2?
Access Control Lists (ACLs) in Magento 2 are used to define permissions for different roles within the system. These roles can then be assigned to users, restricting or granting access to various functionalities based on the defined permissions. By creating custom ACL resources, you can fine-tune the security of your API endpoints, ensuring only authorized users have access.
Learn – How to Implement ACL in Magento 2 Extensions
Steps to Secure API Endpoints with Custom ACL Resources in Magento 2:
Step 1: First, we need to create a webapi.xml file inside our extension at the following path
app\code\Vendor\Extension\etc\webapi.xml
Now add the code as follows
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" ?> <routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd"> <route method="POST" url="/V1/vender-extension/updateproductquantity"> <service class="Vendor\Extension\Api\ProductUpdateInterface" method="UpdateProductQty"/> <resources> <resource ref="Vendor_Extension::product_update"/> </resources> </route> </routes> |
Step 2: Now, we need to create an acl.xml file inside our extension at the following path
app\code\Vendor\Extension\etc\acl.xml
Then add the following code
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> <acl> <resources> <resource id="Magento_Backend::admin"> <resource id="Vendor_Extension::product_update" title="Product Update API" sortOrder="10"/> </resource> </resources> </acl> </config> |
Step 3: Now, we need to create a di.xml file inside our extension at the following path
app\code\Vendor\Extension\etc\di.xml
Then include below-mentioned code
1 2 3 4 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Vendor\Extension\Api\ProductUpdateInterface" type="Vendor\Extension\Model\Api\ProductUpdateApi"/> </config> |
Step 4: Now, we need to create a ProductUpdateInterface.php file inside our extension at the following path
app/code/Vendor/Extension/Api/ProductUpdateInterface.php
And then add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php namespace Vendor\Extension\Api; interface ProductUpdateInterface { /** * @param string $productSku * @param int $productQty * @return string */ public function UpdateProductQty($productSku,$productQty); } |
Step 5: Now, we need to create a ProductUpdateApi.php file inside our extension at the following path
app/code/Vendor/Extension/Model/Api/ProductUpdateApi.php
After that, add the below piece of code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php namespace Vendor\Extension\Model\Api; use Magento\Catalog\Model\ProductRepository; use Magento\CatalogInventory\Api\StockRegistryInterface; class ProductUpdateApi implements \Vendor\Extension\Api\ProductUpdateInterface { protected $productRepository; protected $stockRegistry; public function __construct( ProductRepository $productRepository, StockRegistryInterface $stockRegistry ) { $this->productRepository = $productRepository; $this->stockRegistry = $stockRegistry; } public function UpdateProductQty($sku,$qty){ try { $response = ''; if ($sku == "" || $qty=="") { $response = ["status" => false, "message" => 'Invalid Parameter.']; return json_encode($response); } $product = $this->productRepository->get($sku); if($product->getTypeId() == "configurable") { $response = [ 'status' => false, 'message' => __('Cannot update quantity for configurable product SKU.') ]; return json_encode($response); } if($product->getTypeId() == "grouped") { $response = [ 'status' => false, 'message' => __('Cannot update quantity for grouped product SKU.') ]; return json_encode($response); } if($product->getTypeId() == "bundle") { $response = [ 'status' => false, 'message' => __('Cannot update quantity for bundle product SKU.') ]; return json_encode($response); } $stockItem = $this->stockRegistry->getStockItemBySku($sku); $stockItem->setQty($qty); $stockItem->setIsInStock((bool)$qty); $this->stockRegistry->updateStockItemBySku($sku, $stockItem); $response = [ 'status' => true, 'message' => __('Product quantity updated successfully.') ]; return json_encode($response); } catch (\Exception $e) { return $e->getMessage(); } } } |
Assign Api Resource
How to Execute the Product Quantity Update API?
Step 1: Generate Admin Authorization Token
To interact with the Magento 2 API, you first need to generate an admin authorization token. This token is used to authenticate your requests.
API Type: POST
URL: {{Base_url}}/rest/all/V1/integration/admin/token
Parameters:
1 2 3 4 5 6 7 |
{ "username": "string", "password": "string" } |
Response: “authorization_token”
Step 2: Execute Product Quantity Update API
Use the authorization token obtained in Step 1 to call the Product Quantity Update API.
API Type: POST
Headers:
Authorization: Bearer authorization_token
URL: {{Base_url}}/rest/V1/vender-extension/updateproductquantity
Parameters:
1 2 3 4 5 6 7 |
{ "productSku": "simple", "productQty": 10 } |
Response:
1 2 3 4 5 6 7 |
{ "status": true, "message": "Product quantity updated successfully." } |
Note: You need to pass the admin authorization token in the API header to execute this API. If the authorization token is valid, it will return a success response.
Conclusion:
Securing your Magento 2 API endpoints with custom ACL resources ensures that only authorized users can access sensitive data. By following the steps outlined in this blog, you can create, configure, and assign custom ACL resources to protect your API endpoints effectively.
Implementing these measures not only enhances security but also helps in maintaining a robust and secure eCommerce platform. Remember, a secure platform builds trust with your customers, ultimately leading to a successful online business.
Happy Coding!