Retrieve Customer ID from Bearer Token in Magento 2 API

Retrieve Customer ID from Bearer Token in Magento 2 API

This guide will show you how to retrieve customer ID from Bearer token in the API header of Magento 2. Magento 2 enables you to fetch the customer ID from the Web API Authorization Bearer Token. In the development phase, it’s crucial to retrieve this customer ID from the token included in the header. Use the provided code snippet to easily extract the customer ID from the payload.

<?php
declare(strict_types=1);

namespace Vendor\Module\Api;

use Magento\Framework\Exception\AuthorizationException;
use Magento\Integration\Api\Exception\UserTokenException;
use Magento\Integration\Api\UserTokenReaderInterface;
use Magento\Integration\Api\UserTokenValidatorInterface;
use Magento\Framework\Webapi\Request;

class TokenCustomerId
{
    public function __construct(
        private readonly Request $request,
        private readonly UserTokenReaderInterface $userTokenReader,
        private readonly UserTokenValidatorInterface $userTokenValidator
    ) {
    }

    /**
     * Get customer id based on the authorization token.
     *
     * @return int|null
     * @throws AuthorizationException
     */
    public function getCustomerIdByBearerToken(): ?int
    {
        $authorizationHeaderValue = $this->request->getHeader('Authorization');
        if (!$authorizationHeaderValue) {
            return null;
        }
        $headerPieces = explode(" ", $authorizationHeaderValue);
        if (count($headerPieces) !== 2) {
            return null;
        }

        $tokenType = strtolower($headerPieces[0]);
        if ($tokenType !== 'bearer') {
            return null;
        }

        $bearerToken = $headerPieces[1];
        try {
            $token = $this->userTokenReader->read($bearerToken);
        } catch (UserTokenException $exception) {
            throw new AuthorizationException(__($exception->getMessage()));
        }

        try {
            $this->userTokenValidator->validate($token);
        } catch (AuthorizationException $exception) {
            return null;
        }
        return (int) $token->getUserContext()->getUserId();
    }
}

Leave a Reply

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