Asp.net

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

  • January 23, 2019

為什麼下面的程式碼在我執行我的 Web 應用程序 localhost 時可以正常工作,但在我將其安裝到 IIS 伺服器時卻不行?

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

請不要建議我堅持,HttpContext.Current.User因為它不提供對 SID 或 UPN 的訪問,而無需額外呼叫 Active Directory。

Web 應用程序將由來自三個獨立域的 Windows 身份驗證使用者使用,Web 伺服器託管在第四個域中。應用程序池配置為在NetworkService身份下執行,並且 Web 應用配置將身份模擬設置為 true。

在 IIS 上執行時的錯誤消息是:

Page_Load() 中的錯誤:UserPrincipal.Current。

System.InvalidCastException:無法將“System.DirectoryServices.AccountManagement.GroupPrincipal”類型的對象轉換為“System.DirectoryServices.AccountManagement.UserPrincipal”類型。

在 System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)

在 System.DirectoryServices.AccountManagement.UserPrincipal.get_Current()

在 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);

似乎需要一些其他方法來確定使用者。

這裡來自 msdn 的屬性描述:

“獲取代表目前執行執行緒的使用者的使用者主體對象。”

因此,UserPrincipal.Current 返回執行 IIS 的使用者。

http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.aspx

我在部署 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 作為使用者名傳遞給該方法。

引用自:https://stackoverflow.com/questions/11138373