I want to get admin user details by providing a token via HTTP header. How could I retrieve admin user details of this on Rest API.
3 Answers
A bit late but for future reference:
I assume you are talking about getting the admin user details during an authenticated REST request with an integration admin token. In that case you don't need to get the admin user ID from the token yourself because Magento does already associate the request with an admin ID in the authentication process. Thanks to that you can just use the UserContext
class, to get the ID and the UserFactory
class to get the user model and load it via ID.
use Magento\Authorization\Model\UserContextInterface;
use Magento\User\Model\UserFactory;
...
class YourClass {
private UserContextInterface $userContext;
private UserFactory $userFactory;
...
public function __construct(
UserContextInterface $userContext,
UserFactory $userFactory
)
{
$this->userContext = $userContext;
$this->userFactory = $userFactory;
...
}
public function getAdminUser()
{
$userId = $this->userContext->getUserId();
$user = $this->userFactory->create()->load($userId);
return $user;
}
}
Disclaimer: Yes, ->load($id)
is deprecated. However, at the time of writing this answer, it is still used in the Magento core since service contracts haven't been implemented for the admin user model so far. Corrections are welcome.
If, however, this is not your context and you're looking to get an admin user explicitly by a token string (from a custom header?), you can have a look at the Magento\Webapi\Model\Authorization\TokenUserContext
class and use or reproduce its ->processRequest()
method:
protected function processRequest()
{
if ($this->isRequestProcessed) {
return;
}
$authorizationHeaderValue = $this->request->getHeader('Authorization');
if (!$authorizationHeaderValue) {
$this->isRequestProcessed = true;
return;
}
$headerPieces = explode(" ", $authorizationHeaderValue);
if (count($headerPieces) !== 2) {
$this->isRequestProcessed = true;
return;
}
$tokenType = strtolower($headerPieces[0]);
if ($tokenType !== 'bearer') {
$this->isRequestProcessed = true;
return;
}
$bearerToken = $headerPieces[1];
$token = $this->tokenFactory->create()->loadByToken($bearerToken);
if (!$token->getId() || $token->getRevoked() || $this->isTokenExpired($token)) {
$this->isRequestProcessed = true;
return;
}
$this->setUserDataViaToken($token);
$this->isRequestProcessed = true;
}
- Take $_SERVER['HTTP_AUTHORIZATION']
- Parse the token from that by stripping out the "Bearer " text
- Look up this token in the table oauth_token and you can get the customer ID, admin user ID or integration ID
i know that it's not possible yet. You have to create a web services that allow you to use method loadByUsername of \Magento\User\Model\User