簡體   English   中英

如何從 Windows 10 獲取當前 Azure Active Directory (AAD) 用戶 email

[英]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#. 我可以獲得以下信息:

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 (test.user@testtenant.onmicrosoft.com):

Windows 10 用戶信息

我查看了currentIdentity object 的所有屬性,但在任何地方都看不到,這可能嗎?

您必須使用 System.Security.Claims.ClaimTypes.Upn

這會給你 test.user@testtenant.onmicrosoft.com

如果您使用的是 .NET 3.5 及更高版本,則可以使用UserPrincipal.Current屬性:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find current user
UserPrincipal user = UserPrincipal.Current;

if(user != null)
{
   string loginName = user.SamAccountName; // or whatever you mean by "login name"
}    

InvalidCastException 也有類似的問題: https://stackoverflow.com/a/31819930/13308381

因為有問題的計算機是 Azure 注冊的,它不被視為在域(即本地網絡域)上,因此任何涉及連接到PrincipalContext的操作都會失敗。 用戶的UPN也不存儲在WindowsIdentity object中,大概是為了安全?

可以使用類似以下內容從secur32.dll中的GetUserNameEx方法中檢索它:

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 租戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM