gpt4 book ai didi

asp.net - ASP.NET 中的 ActiveDirectory 当前用户名

转载 作者:行者123 更新时间:2023-12-04 12:23:38 25 4
gpt4 key购买 nike

我正在尝试让 ActiveDirectory 和标准表单登录工作,但有一件事阻止了我。我无法获取当前 Windows 用户的名称。我得到的最接近的是var i = WindowsIdentity.GetCurrent(); ,但这给了我 IIS 应用程序池用户的名称。我在 IIS 中启用了匿名身份验证、表单例份验证和 Windows 身份验证。我可以从 AD 加载用户,所以我假设我的 web.config 设置正确。

编辑 :这是我的 web.config(使用 Facade 提供程序):

<membership defaultProvider="HybridMembershipProvider">
<providers>
<clear />
<add name="HybridMembershipProvider" type="MyApp.Data.HybridMembershipProvider" AspNetProviderName="AspNetSqlMembershipProvider" ActiveDirectoryProviderName="ADMembershipProvider" />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyAppConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
<add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" enableSearchMethods="true" attributeMapEmail="mail"/>
</providers>
</membership>

编辑 2:这是我的 IIS 安全设置。

IIS Security setup

最佳答案

如果你在 IIS 中打开 ASP.Net Impersonation,你可以得到你想要的用户名。这仅在该数据位于成员资格提供者/AD 表单中且它们不是匿名的情况下才有效。

此外,混合基于表单和基于 Windows/AD 的身份验证是可行的,但不推荐。见 this如果你需要这样做。

编辑 :我想我误解了你想要的,所以这里是对上述解决方案的高级解释:

如果您关闭匿名身份验证并打开 Asp.Net 模拟,IIS 将在有人访问该站点时执行 401 质询。
如果一切都在同一个域中,则 Web 浏览器会将您的凭据发送到 IIS,IIS 将根据其 Active Directory 验证它们,然后 AD 将为 IIS 提供一个可以使用的身份。

当您打开 Asp.Net Impersonation 时,IIS 会将该身份绑定(bind)到当前线程/请求。因此,在身份验证发生后,您可以从当前线程标识中获取用户名,然后查询 Active Directory,如下所示:

using System.Threading;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

......

PrincipalContext pc = null;
UserPrincipal principal = null;

try
{
var username = Thread.CurrentPrincipal.Identity.Name;
pc = new PrincipalContext(ContextType.Domain, "active.directory.domain.com");
principal = UserPrincipal.FindByIdentity(pc, username);

var firstName = principal.GivenName ?? string.Empty
var lastName = principal.Surname ?? string.Empty
return string.Format("Hello {0} {1}!", firstName, lastName);
}
catch ...
finally
{
if (principal != null) principal.Dispose();
if (pc != null) pc.Dispose();
}

关于asp.net - ASP.NET 中的 ActiveDirectory 当前用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10584545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com