Back to Top

How to get Access Token of logged in customer in Magento2

Updated 26 March 2024

Here, I am going to explain that how to get access token of logged in customer. In Authorisation process of Rest Api we need to provide access token.

We can get access token using following code. I assume that i have already installed demo magento2 module. I will create only controller file. In which adding  code for getting access token.

<?php

namespace Test\Module\Controller\Test;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;

class Token extends \Magento\Customer\Controller\AbstractAccount
{
    /**
    * @var \Magento\Customer\Model\Session
    */
    protected $_customerSession;

    /**
    * @param Context          $context
    * @param Session          $customerSession
    * @SuppressWarnings(PHPMD.ExcessiveParameterList)
    */
    public function __construct(
        Context $context,
        Session $customerSession,
        \Magento\Integration\Model\Oauth\TokenFactory $tokenModelFactory
    ) {
        $this->_customerSession = $customerSession;
        $this->_tokenModelFactory = $tokenModelFactory;
        parent::__construct(
            $context
        );
    }

    public function execute()
    {
        $customerId = $this->_customerSession->getCustomer()->getId();
        $customerToken = $this->_tokenModelFactory->create();
        echo "Customer-token=> ".$tokenKey = $customerToken->createCustomerToken($customerId)->getToken();
    }
}

You can check in execute function. First line we get logged in customer id from customer session. In second line we create object for \Magento\Integration\Model\Oauth\TokenFactory .

Using this object create customer token by calling createCustomerToken function. Now you can run this controller and get customer access token.

I hope this blog will help you.If any query then you can comment below.Thanks

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

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


1 comments

  • Varun M
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home