How to get customer id from API header bearer token Magento 2?

You can fetch the customer ID from the Web API Header Authorization Token in Magento 2.

At the development time of a custom module, you are required to fetch the customer ID from the Bearer token passed in the Header.

You can just follow the given code snippet to fetch the customer ID from the current payload.

<?php
declare(strict_types=1);

namespace Rbj\Model\Webapi;

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

Using the above code, You can fetch the current customer ID passed in the Authorization Header API request.