asp.netimpersonationuserprincipal

System.DirectoryServices.AccountManagement.UserPrincipal - localhost but not iis


Why does the code below work fine when I run my web application localhost but not when I install it to an IIS server?

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

Please don't suggest I stick with HttpContext.Current.User as it doesn't provide access to SID or UPN without additional calls to Active Directory.

The web application will be used by Windows authenticated users from three separate domains, the web server is hosted in a fourth domain. The Application Pool is configured to run under the NetworkService identity and the web app configuration has identity impersonation set to true.

The error message when it runs on IIS is:

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)

EDIT: Tried both the following and unfortunately get the same error.

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

Solution

  • It seems like need some other method to determine user.
    Here description from msdn for property:
    "Gets a user principal object that represents the current user under which the thread is running."
    So, UserPrincipal.Current returns user under what IIS running.

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