How to Get Admin Username from Session in Magento 2
Learn how to retrieve the currently logged-in admin user's username using session in Magento 2.
Overview
In Magento 2, you can access the admin user's session using the backend authentication session model. This allows you to fetch details like username, user ID, and more.
Step-by-Step Implementation
- Inject the Auth Session class into your constructor.
- Use the session object to get the current user.
- Fetch the username using the
getUserName()method.
Code Example
namespace Vendor\Module\Model;
use Magento\Backend\Model\Auth\Session as AdminSession;
class GetAdminUser
{
protected $adminSession;
public function __construct(AdminSession $adminSession)
{
$this->adminSession = $adminSession;
}
public function getAdminUsername()
{
$user = $this->adminSession->getUser();
if ($user) {
return $user->getUserName();
}
return null;
}
}
Alternative Data You Can Fetch
- User ID:
$user->getId() - Email:
$user->getEmail() - First Name:
$user->getFirstname() - Last Name:
$user->getLastname()
Important Notes
- This works only in the adminhtml area.
- Make sure your code executes when an admin user is logged in.
- Avoid using Object Manager directly; always use Dependency Injection.