'Get UserPrincipalName of logged-on user when windows system has joined into Azure AD
Trying to get UPN (UserPrincipalName) of logged-on user on Windows 10 (and all the logged-on users on Windows 2012 R2) system joined into Azure AD.
Used TranslateNameW API (https://docs.microsoft.com/en-us/windows/desktop/api/secext/nf-secext-translatenamew) in my Win32 native service based application to get UPN of logged-on user. It is working fine on the system joined into on-premise AD.
wchar_t user_sam[512] = { 0 };
wchar_t user_upn[1024] = { 0 };
DWORD len = sizeof(user_upn);
swprintf_s(user_sam, L"%ws\\%ws", L"AAD", L"naga");
BOOL got_upn = TranslateNameW(user_sam, NameSamCompatible, NameUserPrincipal, user_upn, &len);
if (! got_upn)
wprintf(L"Failed to get user upn for %ws: %ld", user_sam, GetLastError());
This API fails on the system joined into Azure AD, getting the error > The specified domain either does not exist or could not be contacted.
Solution 1:[1]
You can use GetUserNameEx with NameUserPrincipal. Here is a working example:
wchar_t user_upn[1024] = { 0 };
DWORD len = sizeof(user_upn);
if (GetUserNameExW(NameUserPrincipal, user_upn, &len))
{
std::wcout << "Username=" << user_upn << std::endl;
}
Actually this function is the one that whoami command executes when you use /UPN as parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Prikryl |
