c# - 尝试 UserPrincipal.FindByIdentity 时出现登录失败错误

标签 c# asp.net

一段时间以来,我一直在寻找解决方案,但不幸的是,每个线程都是死胡同。

我正在开发一个仅供我们公司内部使用的 C#/ASP.net 网络应用程序。 IIS 和我的 web.config 文件中的匿名访问已被关闭,强制 IIS 使用经过 Windows 身份验证的用户(Active Dir 用户)。

我的问题是以下代码可以完美地获取所需的(或任何)AD 用户:

using System.DirectoryServices.AccountManagement;

... other code ...

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain", "someADuser", "someADuserpassword");
UserPrincipal winuser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "samaccountname");

上面 PrincipalContext 中使用的“someADuser”是当前通过 windows 登录的用户,因此经过身份验证并且是有效的 AD 用户。使用以下代码(完全相同的用户仍然登录)给我一个“登录失败:未知的用户名或错误的密码”错误:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain");
UserPrincipal winuser = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "samaccountname");

如果 PrincipalContext 对象中未指定,UserPrincipal.FindByIdentity 似乎出于某种原因不使用已登录用户的验证凭据 - 这是我不想做的事情。

是否有可能 ctx 出于某种原因没有获取登录的 Windows 用户,即使必要的设置(我希望)已添加到 web.config 中:

<authentication mode="Windows"/>
<authorization>
  <deny users="?"/>
</authorization>

匿名访问在 IIS 中被完全禁用了吗?

最佳答案

It seems UserPrincipal.FindByIdentity doesn't use the logged in user's validated credentials for some reason if it's not specified in the PrincipalContext object - something I don't want to do.

UserPrincipal.FindByIdentity 根本不关心用户的凭据。您只是执行查找以查看该帐户是否存在。您收到错误的原因是因为默认用户凭据(即您的 Web 应用程序运行的身份)无权访问该目录,因此它无法执行查找。当您将客户端的凭据传递给 PrincipalContext 时,问题就消失了,因为您的客户端具有可以访问该目录的有效 AD 帐户。

您应该调查正在使用哪个身份来运行应用程序池,并确保它有权访问该目录。

关于c# - 尝试 UserPrincipal.FindByIdentity 时出现登录失败错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15903237/

相关文章:

c# - WPF AppDomain UnhandledException 处理程序超时

c# - 如何从具有封闭 SMTP 端口的安全网络发送电子邮件

c# - 如何将 char[item] 添加到字符串?

c# - Entityframework 是否在创建时自动分配导航属性

asp.net - 如何使用jquery打开aspx页面

c# - ASP.NET Core WebAPI 崩溃是因为我没有 StaticFileMiddleware?

c# - 如何在一定时间后自动删除sql server中的记录

asp.net - Web 环境中线程的注意事项

asp.net - 使用 CQRS 模式在 API 中返回有意义的错误

javascript - 如何将变量从 jQuery 传递到 SqlDataSource 中的 SelectCommand?