Search code examples
web-servicesactive-directorywindows-services

How to get the user's Active Directory groups from web service hosted in a Windows service


I have a web application that stores documents on the server. In some cases I need to place certain permissions per the user groups as they are stored in Active Directory.

I've setup a web service hosted in a Windows service on the server, and the server is making contact with this web service to get the data.

When I call the methods from a regular console application, everything works great, and also if I call the web service when hosted locally on my computer in a Windows service, everything works great as well.

The problem only occurs when on the server - my guess is that when no one is logged on to the server.

Edit: The user is found (I think) and I get "No groups found" as a result.

===========

Another Edit: I updated the code with further work I'm trying.

After many experiments method2 does not fit at all. Method2 requires me to do logon to the system with the user I want to check in order to get his groups. This is something that cannot be done as I don't have that user password.

I believe the two other methods (1 & 3) are not working due to something with the network structure and will have to talk to my boss about it. I will update again if I have some progress.

===========

Here is a link to a C# code I use to get the groups, 3 different methods - none of them work.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class ActiveDirectoryService : System.Web.Services.WebService
{
        [WebMethod]
        public string GetGroups1(string endUsername)
        {
            string result;
            try
            {
                var list = new List<string>();
                var domain = ConfigurationManager.AppSettings["Domain"];
                var serviceUsername = ConfigurationManager.AppSettings["Username"];
                var password = ConfigurationManager.AppSettings["Password"];
                var context = new PrincipalContext(ContextType.Domain, domain, serviceUsername, password);
                var userPrincipal = UserPrincipal.FindByIdentity(context, endUsername);

                if (userPrincipal == null)
                {
                    return "Failed to find user: " + endUsername;
                }

                var authorizationGroups = userPrincipal.GetAuthorizationGroups();
                WriteToLogDebug("GetGroups1.authorizationGroups.Count: " + authorizationGroups.Count());
                foreach (var current in authorizationGroups)
                {
                    if (current is GroupPrincipal)
                    {
                        var groupPrincipal = current as GroupPrincipal;
                        var groupPrincipalName = groupPrincipal?.Name;
                        if (!string.IsNullOrWhiteSpace(groupPrincipalName))
                        {
                            list.Add(groupPrincipalName);
                        }
                    }
                }

                if (!list.Any())
                {
                    result = "No groups found for user " + endUsername;
                }
                else
                {
                    result = string.Join(" & ", list);
                }
            }
            catch (Exception ex)
            {
                result = "Failed to get groups for user " + endUsername + ": " + ex.Message;
                WriteToLogException("GetGroups1." + ex.Message);
            }
            return result;
        }

        [WebMethod]
        public string GetGroups2(string endUsername)
        {
            string result;
            var serviceUsername = ConfigurationManager.AppSettings["Username"];

            try
            {
                var list = new List<string>();

                IntPtr token = GetLogonUserToken();
                if (token == default(IntPtr))
                {
                    return "Failed to logon user: " + serviceUsername;
                }

                var windowsIdentity = new WindowsIdentity(token);
                WriteToLogDebug("GetGroups2.windowsIdentity.Groups.Count: " + windowsIdentity.Groups.Count());

                foreach (var current in windowsIdentity.Groups)
                {
                    try
                    {
                        list.Add(current.Translate(typeof(NTAccount)).ToString());
                    }
                    catch (Exception ex)
                    {
                        WriteToLogException("GetGroups2." + ex.Message);
                    }
                }
                if (!list.Any())
                {
                    result = "No groups found for user " + serviceUsername;
                }
                else
                {
                    result = string.Join(" & ", list);
                }
            }
            catch (Exception ex)
            {
                result = "Failed to get groups for user " + serviceUsername + ": " + ex.Message;
                WriteToLogException("GetGroups2." + ex.Message);
            }
            return result;
        }

        [WebMethod]
        public string GetGroups3(string endUsername)
        {
            var result = "No groups found";
            try
            {
                var directoryEntry = GetDirectoryEntry();
                if (directoryEntry == null)
                {
                    result = "DirectoryEntry returned null";
                }
                else
                {
                    var list = new List<string>();
                    var directorySearcher = new DirectorySearcher(directoryEntry)
                    {
                        Filter = "(&(sAMAccountName=" + endUsername + "))"
                    };
                    if (directorySearcher == null)
                    {
                        WriteToLogDebug("GetGroups3.(directorySearcher == null): " + (directorySearcher == null));
                        return "Failed to initiate directorySearcher";
                    }

                    SearchResultCollection searchResultCollection = null;
                    try
                    {
                        searchResultCollection = directorySearcher.FindAll();
                        if (searchResultCollection == null)
                        {
                            WriteToLogDebug("GetGroups3.(searchResultCollection == null): " + (searchResultCollection == null));
                            return "Failed to find user: " + endUsername;
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteToLogException("GetGroups3.Failed: " + ex.Message);
                        return "Failed to find user " + endUsername + ": " + ex.Message;
                    }

                    if (searchResultCollection.Count == 0)
                    {
                        result = "No groups found for user " + endUsername;
                    }
                    else
                    {
                        WriteToLogDebug("GetGroups3.searchResultCollection.Count: " + searchResultCollection.Count);
                        foreach (var current in searchResultCollection)
                        {
                            var searchResult = current as SearchResult;
                            foreach (var group in searchResult?.Properties["memberOf"])
                            {
                                if (group != null)
                                    list.Add(group.ToString());
                            }
                        }
                        result = string.Join(" & ", list);
                    }
                }
            }
            catch (Exception ex)
            {
                result = "Failed to get groups for user " + endUsername + ": " + ex.Message;
                WriteToLogException("GetGroups3.Failed: " + ex.Message);
            }
            return result;
        }

        private IntPtr GetLogonUserToken()
        {
            try
            {
                var LOGON32_LOGON_INTERACTIVE = 2;
                //var LOGON32_LOGON_NETWORK = 3;
                //var LOGON32_LOGON_BATCH = 4;
                //var LOGON32_LOGON_SERVICE = 5;
                //var LOGON32_LOGON_UNLOCK = 7;
                //var LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
                //var LOGON32_LOGON_NEW_CREDENTIALS = 9;

                var LOGON32_PROVIDER_DEFAULT = 0;

                var domain = ConfigurationManager.AppSettings["Domain"];
                WriteToLogDebug("GetLogonUserToken.domain: " + domain);
                var serviceUsername = ConfigurationManager.AppSettings["Username"];
                WriteToLogDebug("GetLogonUserToken.serviceUsername: " + serviceUsername);
                var password = ConfigurationManager.AppSettings["Password"];
                WriteToLogDebug("GetLogonUserToken.password: " + password);
                LogonUser(serviceUsername, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out IntPtr token);
                return token;
            }
            catch (Exception ex)
            {
                WriteToLogException("GetLogonUserToken.Failed" + ex.Message);
            }
            return default(IntPtr);
        }

        private DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry result;
            try
            {
                var domain = ConfigurationManager.AppSettings["Domain"];
                WriteToLogDebug("GetDirectoryEntry.domain: " + domain);
                var serviceUsername = ConfigurationManager.AppSettings["Username"];
                WriteToLogDebug("GetDirectoryEntry.serviceUsername: " + serviceUsername);
                var password = ConfigurationManager.AppSettings["Password"];
                WriteToLogDebug("GetDirectoryEntry.password: " + password);
                result = new DirectoryEntry
                {
                    Username = serviceUsername,
                    Password = password,
                    Path = "LDAP://" + domain
                };
            }
            catch (Exception ex)
            {
                result = null;
                WriteToLogException("GetDirectoryEntry.Failed: " + ex.Message);
            }
            return result;
        }

Any suggestions how to get a user groups from a web service hosted by a windows service?

Thanks


Solution

  • At the end it was indeed a network block, after changing the domain used I managed to get the end users and their groups. Thank you all for the help.