Magento – How to use token base Rest API

apimagento-2.1magento2rest

I have created custom module and also implemented API in that but I want to
know other two ways Auth base and Token base access.
My webapi.xml file:-

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
<route url="/V1/brand/getList" method="GET">
    <service class="Ktpl\BrandManagement\Api\BrandRepositoryInterface" method="getList"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

I am able to get all the brand list but want to make this request more safer using auth and token base request.

Best Answer

In magento web-API when you pass user name and password then it genrates token for that specific customer (Which is only valid for 1 hour - configurable from admin)

http://magento.host/index.php/rest/V1/integration/customer/token?username=test.user@test.com&password=test@123

webapi.xml code

<route url="/V1/customers/me" method="GET">
    <service class="Magento\Customer\Api\CustomerRepositoryInterface" method="getById"/>
    <resources>
        <resource ref="self"/>
    </resources>
    <data>
        <parameter name="customerId" force="true">%customer_id%</parameter>
    </data>
</route>

which returns token.

After genrating token, when we pass that token in header.

Authorization :: Bearer <Token Value>

http://magento.host/index.php/rest/V1/customers/me

Which returns customer detailes.

The above case i explained is working fine for webAPI in magento2 which i tested in POSTMAN.