How to Get Customer Access Token by Logged-in Customers in Magento 2

How to Get Customer Access Token of Logged in Customers in Magento 2?

In today’s tutorial, we will guide you with a step-by-step process to get customer access tokens of logged-in customers in Magento 2. During the authorization process of the Rest API, the customer access token is necessary. The below-mentioned code can help you get access tokens. 

Prerequisite – Demo Magento 2 module. 

In Magento 2, a customer token is valid for 1 hour by default. But if you want to update the value of customer token expire time, follow the below-mentioned path:

Go to Admin -> Stores -> Configuration -> Services -> OAuth -> Access Token Expiration -> Customer Token Lifetime (hours)

<?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();
    }
}

Here, we have created a controller file. Now, all you need to do is to run the controller and get a customer access token. We hope that we’ve cleared everything related to getting customer access token. If there is any query, feel free to reach us out.

Tags