Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I secure my custom Magento2 REST api

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

like image 843
Oved Yavine Avatar asked Sep 01 '16 07:09

Oved Yavine


3 Answers

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

like image 175
vijay b Avatar answered Oct 14 '22 14:10

vijay b


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.

like image 45
Garvin Avatar answered Oct 14 '22 13:10

Garvin


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

like image 27
Alex Gusev Avatar answered Oct 14 '22 14:10

Alex Gusev