Question

I have an ASP.NET application that runs on our intranet. In production I can get the user from the domain context and have access to lots of information including their first and last name (UserPrincipal.GivenName and UserPrincipal.Surname).

Our test environment is not part of the production domain and test users do not have domain accounts in the test environment. So, we add them as local machine users. They are prompted for credentials when they browse to the start page. I use the following method to get the UserPrincipal

public static UserPrincipal GetCurrentUser()
        {
            UserPrincipal up = null;

            using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
            {
                up = UserPrincipal.FindByIdentity(context, User.Identity.Name);
            }

            if (up == null)
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Machine))
                {
                    up = UserPrincipal.FindByIdentity(context, User.Identity.Name);
                }
            }

            return up;
        }

The problem I have here is that when the UserPrinicipal is retrived when ContextType == Machine I do not get properties like GivenName or Surname. Is there a way to set these values when creating the user (Windows Server 2008) or do I need to go about this in a different way?

Was it helpful?

Solution

The function in the original question needs to be modified. If you try to access the UserPrincipal object that is returned, you will get an ObjectDisposedException

Also, the User.Identity.Name is not available and needs to be passed in.

I have made the following changes to the function above.

public static UserPrincipal GetUserPrincipal(String userName)
        {
            UserPrincipal up = null;

            PrincipalContext context = new PrincipalContext(ContextType.Domain);
            up = UserPrincipal.FindByIdentity(context, userName);

            if (up == null)
            {
                context = new PrincipalContext(ContextType.Machine);
                up = UserPrincipal.FindByIdentity(context, userName);
            }

            if(up == null)
                throw new Exception("Unable to get user from Domain or Machine context.");

            return up;
        }

Furthermore, the property of UserPrincipal I need to use is DisplayName (instead of GivenName and Surname);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top