🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How To Get Access Token Of Logged In Customer In Magento 2

By Sanjay JethvaUpdated on May 22, 2025 1 min read

The post shows the programmatic method to get access token of logged in customer in Magento 2.

You can use this method when, for example, you want to improve the login method for customers and allowing them to login via Facebook or Google.

The developer must give the access token to make a web Magento 2 API call from a client such as a mobile application. This token serves as an electronic key to access the API.

Method to get access token of logged in customer in Magento 2:

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Context;
use Magento\Integration\Model\Oauth\TokenFactory;

protected $customerSession;
protected $tokenModelFactory;
 
 
public function __construct(
        Session $customerSession,
        TokenFactory $tokenModelFactory
) {
    $this->customerSession = $customerSession;
    $this->tokenModelFactory = $tokenModelFactory;
        
} 

public function getToken(){
    $customerId = $this->customerSession->getCustomer()->getId();
    $customerToken = $this->tokenModelFactory->create();
    return $customerToken->createCustomerToken($customerId)->getToken();
}

Apart from the programmatic solution, you can also use Magento 2 API to get customer token by calling a GET request with credentials.

That’s it.

Feel free to share the solution with fellow developers via social media.

Thank you.

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.