How To Get Customer Id From Bearer Token In Magento2 Rest API?

In REST API integration, we can retrieve customer token from calling /V1/integration/customer/token API. Later this token is passed as a bearer token in Postman or we can pass in the api_key text field on the top of the page in the user interface for swagger. Sometime we may need to get the customer id from the token.

looking for a magento 2 developer

We need to inject the object for class \Magento\Authorization\Model\CompositeUserContext in __construct() method of your class. CompositeUserContext class has getUserId() method that will retrieve the CustomerId for generated token.

<?php
namespace WebbyTroops\RestApi\Model\Customer;

class Token
{
    /**
     *
     * @var \Magento\Authorization\Model\CompositeUserContext
     */
    protected $userContext;
    
    /**
     * 
     * @param \Magento\Authorization\Model\CompositeUserContext $userContext
     */
    public function __construct(
        \Magento\Authorization\Model\CompositeUserContext $userContext
    ) {
        $this->userContext = $userContext;
    }
    
    /**
     * 
     * @return int
     */
    public function getCustomerId()
    {
        return $customerId = $this->userContext->getUserId();
    }
}

With $this->userContext->getUserId(); you will get the customer id.

Leave A Comment

Go To Top