我需要能够通过 C# 从 Windows 10 检索当前登录的 Azure AD 用户的电子邮件(技术上是 UPN)。我可以获得以下信息:
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"
但我真正需要的是如下电子邮件/UPN ( [email protected] ):
我已经查看了 currentIdentity
对象的所有属性,但在任何地方都看不到它,这可能吗?
最佳答案
由于相关计算机是在 Azure 中注册的,因此它不会被视为在域(即本地网络域)上,因此涉及连接到 PrincipalContext
的任何操作都将失败。用户的 UPN 也没有存储在 WindowsIdentity
对象中,大概是出于安全考虑?
可以从 GetUserNameEx 检索secure32.dll
中的方法,使用如下所示的内容:
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;
}
这显然仅适用于当前用户,大概要检索其他用户的 UPN,您需要使用 Graph API 直接联系 Azure AD 租户。
关于c# - 如何从 Windows 10 获取当前 Azure Active Directory (AAD) 用户电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66805156/