title: autenticating ldap for web applications
body: <p><strong><em>please take a few minutes and read my question completely</em></strong>. here is my problem : 
  I want to connect to LDAP server <strong><em>by C#</em></strong> for a web application, means clients connecting to the asp.net server.</p>
  
  <p>*- The ldap server and application server are not the same.</p>
  
  <p>**- They are not in a same domain. </p>
  
  <p>I have been trying <strong><em>4 different ways</em></strong> and could not solve the problem by none of them. </p>
  
  <p>1- </p>
  
  <pre><code>        var credentials = new NetworkCredential(username, password);
          var serverId = new LdapDirectoryIdentifier("domain.net");
  
          var conn = new LdapConnection(serverId, credentials);
              conn.Bind();
  </code></pre>
  
  <p>2-</p>
  
  <pre><code>System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://domain.net/DC=domain,DC=net");
                  entry.Username = "username";
                  entry.Password = "password";
                  System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(entry);
                  searcher.Filter = "(&amp;(objectClass=user))";
                  var results = searcher.FindAll();
  </code></pre>
  
  <p>the problem with these 2 ways is that the user must have an access to the server for login and we know that there is only admin of the system who has the permission. </p>
  
  <p>3-</p>
  
  <pre><code>   PrincipalContext pc = new PrincipalContext(ContextType.Domain, "domain.net");
     var ret = pc.ValidateCredentials(model.UserName, model.Password);
  </code></pre>
  
  <p>the problem is the server must be in the domain of ldap server. we have this limitation !!</p>
  
  <p>4-</p>
  
  <p><a href="https://auth0.com/blog/using-ldap-with-c-sharp/" rel="nofollow noreferrer">https://auth0.com/blog/using-ldap-with-c-sharp/</a></p>
  
  <pre><code>public bool validateUser(string username, string password)
  {
      var sha1 = new SHA1Managed();
      var digest = Convert.ToBase64String(sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)));
      var request = new CompareRequest(string.Format("uid={0},ou=users,dc=example,dc=com", username),
          "userPassword", "{SHA}" + digest);
      var response = (CompareResponse)connection.SendRequest(request);
      return response.ResultCode == ResultCode.CompareTrue;
  }
  </code></pre>
  
  <p>this code does not return any thing. it will be very helpful if there is a query to compare usernames and passwords. this code seems to use this way but there are different types of hash algorithms. I tried to use SHA1 and MD5, and userPassword , unicodePwd attribute. but the return is empty all the time. </p>
  
  <p>is it the best solution to put both servers in a same domain? any other solution , Thank you so much.</p>