I created a custom REST api in Magento2. But, how do I secure it with the built-in Magento2 REST api security?
just like /index.php/rest/V1/customers/me is secured with the Authorization header
while creating custom api configuration in webapi.xml put ref="self"
if you configured like this you can access API with authentication only provided by magento 2 like oauth,token,oauth2
Disable access for api to anonymous in admin panel of magento
Access Security on Custom api applied through
Magento 2 allows some web APIs to be accessed by unauthenticated (anonymous) users.To prevent access to anonymous user , define a resource to which the caller must have access. Like ,
<route url="/V1/techyrules/webservice/deleteAddressMine" method="PUT">
<service class="techyrules\WebService\Api\AddressManagementInterface" method="deleteAddressMine"/>
<resources>
<resource ref="self"/>
</resources>
</route>
ref, Valid values are self, anonymous, or a Magento resource, such as Magento_Customer::group.
Self example, user authenticate him/herself by username & password then token will be generated in response that token act as self permission for further processes.
Replace <resource ref="anonymous"/>
by <resource ref="Venodr_Module::name_of_the_acl_entry"/>
in the etc/webapi.xml
of your module:
<route url="/V1/customers/me" method="...">
<service class="..." method="..."/>
<resources>
<resource ref="Vendor_Module::name_of_the_acl_entry"/>
<!--<resource ref="anonymous"/>-->
</resources>
</route>
and setup ACL in the etc/acl.xml
:
<?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_Module::name_of_the_acl_entry" title="Human readable title"/>
</resource>
</resources>
</acl>
</config>
Then grant access for concrete backend user in "System / Permissions / User Roles", select Role, tab "Role Resources" and "Resource Access". Select "All" or select "Custom" and check resource named "Human readable title".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With