1

I do not know how to stop to create customers via REST API in magento 2. I have magento 2 instance in 2.4.0 version

I found a below code in vendor/magento/module-customer/etc/webapi.xml path

<route url="/V1/customers" method="POST">
        <service class="Magento\Customer\Api\AccountManagementInterface" method="createAccount"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

Above code to create customer via rest api, how can I disable this flow?

1 Answer 1

1

I think I would utilize Plugin in this case.

Specifically, create a di.xml file in your Vendor_Module/etc/rest directory, declare a plugin for the service class which provides Customer create function.

<config>
    <type name="Magento\Customer\Api\AccountManagementInterface">
      <plugin name="your_plugin_name" type="Vendor\Module\Plugin\AccountManagementPlugin" sortOrder="1" disabled="false" />
    </type>
</config>

Then we're using the around method to stop the createAccount function from executing at all by not calling $proceed().

<?php

namespace Vendor\Module\Plugin;

use Magento\Customer\Api\AccountManagementInterface;

class AccountManagementPlugin
{
    public function aroundSave(
        AccountManagementInterface $subject,
        callable $proceed,
        CustomerInterface $customer,
        $password = null,
        $redirectUrl = ''
    ) {
        // DO NOT call $proceed() at all!
        
        // Other than that you can throw an exception telling that this action is not permitted or so
        // Or do nothing at all, that's fine.
    }
}

One side effect is, any other function that used to/is supposed to call to this createAccount function will not be able to call it at all. If this is not what you would expect, then a fix would be, you can check for the requested URL, if URL is something other than rest/V1/customers, meaning it is calling to a different endpoint, then proceed as usual (by calling $proceed()).

Reference on how to get requested API URL.

Hopefully it works for you!

Happy coding!

1
  • Thank you, I used plugin before for createAccount method and checking url come from API or from create account form Apr 6, 2023 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.