如何在 .NET Web 应用程序中为经过身份验证的用户获取 UPN,而不查询 Active Directory

Mar*_*ica 5 .net active-directory upn

(这个问题类似于Get UPN or email for login user in a .NET web application,但不完全相同。)

在使用 Windows 身份验证的 .NET (C#) Web 应用程序中,我想找到登录用户的 UPN。

我知道如何通过查询 Active Directory 来做到这一点:从HttpContext.Current.User.Identity as WindowsIdentity;获取 'DOMAINNAME\userName' 在 下查找 DOMAINNAMEldap://RootDSE并找到它dnsRoot;查询(&(objectCategory=person)(objectClass=user)(sAMAccountName=...userName...))ldap://...dnsRoot...;获取此条目的userPrincipalName属性。(更多细节在回答/sf/answers/35956791/ 中)。

我的问题:是否可以在调用 Active Directory 的情况下找到 UPN ?鉴于 Microsoft 专注于在任何地方使用 UPN,UPN 是不是已经存储在用户向 Web 服务器进行身份验证时创建的令牌中的某处?

(支持观察:如果我whoami /upn在 Windows 7 上运行,那么 Wireshark 不会显示任何 Active Directory 连接。)

(如果有什么不同:请注意,我们的 Web 应用程序不使用 impersonation,即我们的 Web 应用程序不在用户身份下运行。)

Jac*_* A. 6

我在使用 时遇到了 Active Directory 查询问题System.DirectoryServices.AccountManagement.UserPrincipal.Current,因此我求助于使用GetUserNameExNameUserPrincipal格式。

此函数获取有关当前用户的信息,因此如果您还没有模拟的话,它确实需要您进行模拟。在 C# 中,可以通过导入函数来完成:

public enum EXTENDED_NAME_FORMAT
{
    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.Auto)]
public static extern int GetUserNameEx(int nameFormat, StringBuilder userName, ref int userNameSize);
Run Code Online (Sandbox Code Playgroud)

然后像这样调用它:

string upn = null;
StringBuilder userName = new StringBuilder(1024);
int userNameSize = userName.Capacity;
if (GetUserNameEx((int)EXTENDED_NAME_FORMAT.NameUserPrincipal, userName, ref userNameSize) != 0)
{
    upn = userName.ToString();
}
Run Code Online (Sandbox Code Playgroud)


Hac*_*ese 5

试试System.DirectoryServices.AccountManagement.UserPrincipal.Current,它有属性UserPrincipalName。当然,这需要应用程序在 Windows 身份验证下运行。

编辑Meh,看起来这个 API 仍然执行目录查找。

  • 我不会再尝试这个了,但是使用 `WindowsIdentity.Impersonate()` 加上 `UserPrincipal.Current.UserPrincipalName` 应该可以工作。我将此标记为答案。 (2认同)