Create a web service that negotiates with Active Directory to validate users and determine which groups they belong to.
I started with the verification process and got this working:
public bool AuthenticateAdUser(string username, string password) { //in the real code, these come from config string domain = "TestDomain"; string server = 666.666.666.666; string authType = "Basic"; string useSsl = "false"; AuthType atype = (AuthType)Enum.Parse(typeof(AuthType), authType); using (var ldapConnection = new LdapConnection(server)) { var networkCredential = new NetworkCredential(username, password, domain); ldapConnection.SessionOptions.SecureSocketLayer = Convert.ToBoolean(useSsl); ldapConnection.AutoBind = false; ldapConnection.AuthType = atype; ldapConnection.Bind(networkCredential); } // If the bind succeeds, the credentials are valid return true; }
However, I do not understand how I can use this LdapConnection object to work with groups. The documentation and examples suggest using PrinicpalContext for this purpose. So I tried this.
string domain = "TestDomain"; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain)) { using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, username).GetGroups(pc)) { src.ToList().ForEach(sr => result.Add(sr.SamAccountName)); } }
This fails, claiming that it cannot contact the Active Directory server. Using a DNS style name ("TestDomain.local") does not seem to help.
This, at least, expands the network principal:
string server = "666.666.666.666"; using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, server)) { using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, username).GetGroups(pc)) { src.ToList().ForEach(sr => result.Add(sr.SamAccountName)); } }
But when you try and do something about it, it fails with "Network path not found."
Any ideas on why the Principal will not work, or how can I use LdapConnection for query groups?