You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento 2多店铺REST API按店铺权限限制的扩展或代码方案咨询

Solutions for Magento 2 Multi-Store User Permission Restrictions

Hey there! I’ve tackled this exact problem while building a multi-store Magento 2 instance integrated with desktop software via REST API, so I have both extension-based and custom code solutions to share with you.

Option 1: Use Third-Party Extensions

There are several reliable extensions that handle multi-store user permission restrictions, including support for REST API access:

  • Amasty Multi-Store Access Control: One of the most popular options. It lets you assign specific store views/websites to individual admin users, and automatically filters API requests to only return data from the user’s allowed stores. It also locks down backend access to match the store permissions, making it a full-circle solution.
  • Magefan Multi-Store Admin Permissions: Another solid choice that adds granular store-level restrictions for admins, including REST API request filtering. It supports custom user roles tied to specific stores, making it easy to scale as you add more stores.
  • Webkul’s Magento 2 Multi-Store User Permissions: This extension focuses on store-specific access for both backend users and API consumers, with options to restrict access to orders, products, customers, and other entities per store.

Option 2: Custom Code Implementation

If you prefer a self-hosted solution without relying on third-party extensions, here’s a step-by-step approach:

Step 1: Add a "Allowed Stores" Attribute to Admin Users

First, create a custom module (let’s call it Vendor_StoreRestriction) and add an attribute to store the allowed store IDs for each user. Create an InstallData.php file in your module’s Setup directory:

<?php
namespace Vendor\StoreRestriction\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\User\Model\User;
use Magento\User\Model\ResourceModel\User as UserResource;

class InstallData implements InstallDataInterface
{
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $setup->getConnection()->addColumn(
            $setup->getTable('admin_user'),
            'allowed_store_ids',
            [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                'nullable' => true,
                'comment' => 'Allowed Store IDs (comma-separated)'
            ]
        );
        $setup->endSetup();
    }
}

Step 2: Create a Plugin to Check Store Permissions for API Requests

Next, create a plugin to intercept API permission checks and verify if the user has access to the requested store. Create a AuthorizationPlugin.php file in Vendor/StoreRestriction/Plugin:

<?php
namespace Vendor\StoreRestriction\Plugin;

use Magento\Authorization\Model\Authorization;
use Magento\Framework\App\Request\Http;
use Magento\User\Model\UserFactory;

class AuthorizationPlugin
{
    protected $request;
    protected $userFactory;

    public function __construct(Http $request, UserFactory $userFactory)
    {
        $this->request = $request;
        $this->userFactory = $userFactory;
    }

    public function beforeIsAllowed(Authorization $subject, $resource, $user = null)
    {
        // Skip if no user is provided or we're not in an API context
        if (!$user || !strpos($this->request->getPathInfo(), 'rest/')) {
            return [$resource, $user];
        }

        $currentStoreId = $this->request->getParam('store');
        if (!$currentStoreId) {
            // Fallback to default store if no store parameter is provided
            $currentStoreId = \Magento\Store\Model\Store::DEFAULT_STORE_ID;
        }

        $adminUser = $this->userFactory->create()->load($user->getId());
        $allowedStoreIds = explode(',', $adminUser->getAllowedStoreIds());

        // Deny access if the current store isn't in the user's allowed list
        if (!in_array($currentStoreId, $allowedStoreIds)) {
            return [$resource, null]; // Null user will trigger permission denial
        }

        return [$resource, $user];
    }
}

Step 3: Filter API Response Data by Allowed Stores

To ensure only data from allowed stores is returned, add a plugin to collection classes (e.g., product collection, order collection). For example, create a ProductCollectionPlugin.php:

<?php
namespace Vendor\StoreRestriction\Plugin;

use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\User\Model\UserFactory;
use Magento\Framework\App\Request\Http;

class ProductCollectionPlugin
{
    protected $userFactory;
    protected $request;

    public function __construct(UserFactory $userFactory, Http $request)
    {
        $this->userFactory = $userFactory;
        $this->request = $request;
    }

    public function beforeLoad(Collection $subject)
    {
        if (!strpos($this->request->getPathInfo(), 'rest/')) {
            return;
        }

        $userId = $this->request->getParam('user_id'); // Adjust based on your API auth method
        if (!$userId) {
            return;
        }

        $adminUser = $this->userFactory->create()->load($userId);
        $allowedStoreIds = explode(',', $adminUser->getAllowedStoreIds());

        $subject->addStoreFilter($allowedStoreIds);
    }
}

Step 4: Register Plugins in di.xml

Add the plugin definitions to your module’s etc/di.xml file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Authorization\Model\Authorization">
        <plugin name="vendor_storerestriction_authorization" type="Vendor\StoreRestriction\Plugin\AuthorizationPlugin" />
    </type>
    <type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
        <plugin name="vendor_storerestriction_product_collection" type="Vendor\StoreRestriction\Plugin\ProductCollectionPlugin" />
    </type>
</config>

A few notes to keep in mind:

  • Adjust the auth method (how you get the user ID in the collection plugin) based on your REST API authentication setup (e.g., OAuth, token-based).
  • You’ll need to add similar plugins for other entities like orders, customers, etc., depending on your use case.
  • Test thoroughly to ensure all API requests respect the store restrictions, including write operations (e.g., creating orders should only be allowed for the user’s stores).

内容的提问来源于stack exchange,提问作者Sérgio M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:35:05