Magento2 API – Fix 401 Unauthorized for Accessing Customer API

apimagento-2.1magento2rest api

I was able to get the admin token using the below url against the created admin user
http://username:password@localhost.com/index.php/rest/V1/integration/admin/token

The username and password is for browser authentication which you can see before the url which is defined in .htaccess and .htpassword. The original username and password is given in the body

{
"username":"admin",
"password":"admin123"
}

But when I get customers by passing the token it says 401 unauthorized.
Below is the request

http://username:password@localhost.com/index.php/rest/V1/customers
and token is passed as "Authorization: Bearer abcdefghi" in request header

How to fix this issue?

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.