Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current Azure Active Directory (AAD) user email from Windows 10

I need to be able to retrieve the current logged-on Azure AD user's email (technically a UPN) from Windows 10 via C#. I can get the following information:

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

string userSid =
    currentIdentity.Claims.FirstOrDefault(
        u => u.Type == System.Security.Claims.ClaimTypes.PrimarySid).Value;

string username = currentIdentity.Name; // This returns "AzureAD\\TestUser"

But what I really need is the email/UPN as below ([email protected]):

Windows 10 User Info

I've looked through all properties of the currentIdentity object and can't see it anywhere, is this possible?

like image 857
ataraxia Avatar asked Jan 23 '26 04:01

ataraxia


1 Answers

Because the computer in question is Azure registered, it is not seen as on a domain (i.e. local network domain), therefore any operations involving connecting to a PrincipalContext will fail. The user's UPN is also not stored in the WindowsIdentity object, presumably for security?

It can be retrieved from the GetUserNameEx method in secur32.dll using something like the below:

public enum ExtendedFormat
{
    NameUnknown = 0,
    NameFullyQualifiedDN = 1,
    NameSamCompatible = 2,
    NameDisplay = 3,
    NameUniqueId = 6,
    NameCanonical = 7,
    NameUserPrincipal = 8,
    NameCanonicalEx = 9,
    NameServicePrincipal = 10,
    NameDnsDomain = 12,
}

[DllImport("secur32.dll", CharSet = CharSet.Unicode)]
public static extern int GetUserNameEx(int nameFormat, StringBuilder userName, ref int userNameSize);

public string GetCurrentUPN()
{
    StringBuilder userUPN = new StringBuilder(1024);
    int userUPNSize = userUPN.Capacity;

    if (GetUserNameEx((int)ExtendedFormat.NameUserPrincipal, userUPN, ref userUPNSize) != 0)
    {
        return userUPN.ToString();
    }

    return null;
}

This is obviously for the current user only, presumably to retrieve another user's UPN you'd need to contact the Azure AD tenant directly using the Graph API.

like image 64
ataraxia Avatar answered Jan 25 '26 18:01

ataraxia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!