How To

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!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Organic Traffic Drop: Sudden Decline Causes and Solutions

A sudden drop in organic traffic can be alarming for any business. Organic traffic is…

12 hours ago

Difference Between: Magento 2 WhatsApp Order Notification vs. Magento 2 SMS Notification

In the fast-paced world of eCommerce, effective communication is key to maintaining customer satisfaction and…

12 hours ago

Understanding useSearchParams vs useParams Hooks in Remix

In the Remix framework, handling URL parameters is a common task when building dynamic web…

1 day ago

How to Implement Frontend Design Customization in Shopify Remix App?

In this blog post, we'll show you how to implement frontend design customization in the…

3 days ago

Your Ultimate Guide to Shopify Headless Commerce

Starting an eCommerce business with Shopify can be easy yet challenging in many different ways,…

5 days ago

Magento 2: How to Show Custom Notice Message Before Payment Step on Checkout

Hello Magento Friends, In Magento 2, you can customize the checkout process to enhance the…

5 days ago