c# - 如何从 Windows 10 获取当前 Azure Active Directory (AAD) 用户电子邮件

标签 c# windows azure azure-active-directory

我需要能够通过 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] ):

Windows 10 User Info

我已经查看了 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/

相关文章:

c# - 通过鼠标移动控件

c# - 执行异步 RIA 服务调用时回调在哪个线程上执行?

c# - 应用程序在重新启动之前看不到系统时区更改

azure - updateStartupCommandAndRuntimeStack 错误 azureweapp 部署

azure - 如何使用 Azure SQL Server 数据库设置 SSRS

Azure数据工厂映射数据流: Epoch timestamp to Datetime

c# - 获得形成三角形的最近点

c# - 如何用循环和条件做单行代码?

python exe文件在Windows xp上启动时崩溃

windows - 使用Windows在所有目录中递归执行命令