Magento2 Api Get Admin User Details Inside Magento
-
22-01-2021 - |
题
I'm making a call to Magento API and I need to save the current admin id
POST /rest/V1/precart/create HTTP/1.1
Host: magento2.local
Content-Type: application/json
Authorization: Bearer 59f6t7aso8a37g1hxbkd5ol0pem3cd3b
Cache-Control: no-cache
Postman-Token: 7456cf04-634e-4f6f-acb9-c85ca18d849a
{
"preCart" : {
"sku": "123",
}
}
I tried some suggestions, but I think this only work with normal site session. How I do this by API?
protected $_authSession;
public function __construct(
\Magento\Backend\Model\Auth\Session $authSession,
...
)
{
$this->_authSession = $authSession;
...
}
/**
* Processing data before model save
*
* @return $this
*/
public function beforeSave()
{
if (empty($this->getUserId()) && $user = $this->getCurrentUser()) {
$this->setUserId($user->getId());
}
return parent::beforeSave();
}
/**
* @return \Magento\User\Model\User|null
*/
public function getCurrentUser()
{
return $this->_authSession->getUser();
}
解决方案
We can do this using the user context.
User context store all user authentication types and returns the used.
See at: CompositeUserContext.php
How to use:
/**
* @var \Magento\Authorization\Model\UserContextInterface
*/
protected $_userContext;
/**
* constructor.
* @param \Magento\Authorization\Model\UserContextInterface $userContext
*/
public function __construct(
\Magento\Authorization\Model\UserContextInterface $userContext,
)
{
$this->_userContext = $userContext;
parent::__construct();
}
/**
* @return int
*/
public function getCurrentUserId()
{
return $this->_userContext->getUserId();
}