asp.net - System.DirectoryServices.AccountManagement.UserPrincipal - localhost 但不是 iis

标签 asp.net impersonation userprincipal

为什么下面的代码在我运行 Web 应用程序 localhost 时可以正常工作,但在将其安装到 IIS 服务器时却不能正常工作?

using (HostingEnvironment.Impersonate())
{
    UserPrincipal activeUser = UserPrincipal.Current;
    String activeUserSid = activeUser.Sid.ToString();
    String activeUserUPN = activeUser.UserPrincipalName;
}

请不要建议我坚持使用 HttpContext.Current.User,因为它无法在不额外调用 Active Directory 的情况下提供对 SID 或 UPN 的访问。

Web 应用程序将由来自三个不同域的 Windows 身份验证用户使用,Web 服务器托管在第四个域中。应用程序池配置为在 NetworkService 身份下运行,并且 Web 应用配置将身份模拟设置为 true。

在IIS上运行时的错误信息是:

Error in Page_Load(): UserPrincipal.Current.
System.InvalidCastException: Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()
at webapp.Details.Default.Page_Load(Object sender, EventArgs e)

编辑: 尝试了以下两种方法,不幸的是得到了同样的错误。

UserPrincipal userPrincipal = UserPrincipal.Current;
Response.Write(userPrincipal.Name);
Principal userOrGroup = UserPrincipal.Current;
Response.Write(userOrGroup.Name);

最佳答案

我在部署 UserPrincipal.Current 时遇到了很多问题,但仍然不完全理解原因。

我最终使用了PrincipalSearcher,并创建了以下函数来完成我认为UserPrincipal.Current正在做的事情。

private UserPrincipal GetActiveDirectoryUser(string userName)
{
    using(var ctx = new PrincipalContext(ContextType.Domain))
    using(var user = new UserPrincipal(ctx) { SamAccountName = userName})
    using(var searcher = new PrincipalSearcher(user))
    {
        return searcher.FindOne() as UserPrincipal;
    }
}

我将 System.Web.HttpContext.Current.User.Identity.Name 作为用户名传递到该方法中。

关于asp.net - System.DirectoryServices.AccountManagement.UserPrincipal - localhost 但不是 iis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11138373/

相关文章:

ASP.NET刷新更新面板

javascript - 将 @Html.TextBox 更改为常规 html 代码

asp.net - 根据经过身份验证的用户访问文件共享上的某些文件夹

httpclient - kerberos 委托(delegate)场景下的 ASP 双跳请求

c# - 从机器上下文中获取用户全名

Spring 安全 : setUserPrincipal manually

mysql - 如何在 visual studio 2015 中使用 ADO.net Identity 数据模型使用 Entity Framework 6(web api)进行 mariadb 设置(版本 10.2.17)?

javascript - 使用 JQuery 或 JavaScript 访问 Gridview 内的 Eval 值

c# - 外部程序在模拟启动时崩溃,但在 runas 时运行

c# - 我可以使用 PrincipalContext() 从 Active Directory 获取用户部门吗