Site icon MageComp Blog

Magento 2: How to Secure API Endpoints with Custom ACL Resources

Magento 2 How to Secure API Endpoints with Custom ACL Resources

Hello Magento Friends,

In today’s blog, we will learn about, How to Secure API Endpoints with Custom ACL Resources in Magento 2.

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

<?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

<?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

<?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

<?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

<?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:

{

  "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:

{

  "productSku": "simple",

  "productQty": 10

}

Response:

{

  "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!

Exit mobile version