Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserPrincipal.FindByIdentity returns null on IIS Server

I have following code sample in ASP.NET

        using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain))
        {
            using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, HttpContext.Current.User.Identity.Name))
            {
                if (user == null)
                {
                    lbName.Text = "No User Principal";
                }
                else
                {
                    lbName.Text = user.DisplayName;
                }
            }
        }

The web.config looks like

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

I tried the code on my local development machine (part of domain, logon as domain user, VS2010, .Net 4.0, Windowx XP) to test locally, I am able to get UserPrincipal object.

If I deploy to WIndows 2003 (also part of the domain), IIS6, .Net 4.0 with application pool running under Network Service, I turned off anonymous access. But the code is not able to get UserPrincipal object.

Do I have to change application pool to run under a domain account in order to get UserPrincipal?

like image 711
hardywang Avatar asked Dec 15 '11 15:12

hardywang


1 Answers

The reason it worked on your dev box and not on your prod box is that on your dev box the website ran under your network ID, which had domain rights, but in production it's running under network service which has no rights to your domain. You can either:

  • Change the account the IIS App Pool runs under to a domain one
  • Add an impersonation section to your web.config file, where the account is a domain account
  • Explicitely specify a username/password in your PrincipalContext which will be used to authenticate to the domain.
like image 101
Peter Avatar answered Oct 13 '22 02:10

Peter