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.

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.

<!-- wp:code {"hasCustomCSS":true} -->
<pre class="wp-block-code"><code>/**
 * 
&lt;!-- wp:paragraph -->
&lt;p>class Token&lt;br>{&lt;br>/**&lt;br>*&lt;br>* @var \Magento\Authorization\Model\CompositeUserContext&lt;br>*/&lt;br>protected $userContext;&lt;/p>
&lt;!-- /wp:paragraph -->

 * @param \Magento\Authorization\Model\CompositeUserContext $userContext
 */
public function __construct(
    \Magento\Authorization\Model\CompositeUserContext $userContext
) {
    $this-&amp;gt;userContext = $userContext;
}

/**
 * 
 * @return int
 */
public function getCustomerId()
{
    return $customerId = $this-&amp;gt;userContext-&amp;gt;getUserId();
}</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>With $this-&gt;userContext-&gt;getUserId();</h4>
<!-- /wp:heading -->

With $this->userContext->getUserId();

2 thoughts on “How To Get Customer Id From Bearer Token In Magento2 Rest API?”

  1. Hey there! Do you use Twitter? I’d like to follow you if that
    would be ok. I’m definitely enjoying your blog and look forward to new updates.

Leave a Reply

Your email address will not be published. Required fields are marked *