title: How to check for user credentials using active directory and a ruby script
body: <p>I'm trying write a Ruby script that checks if user credentials are valid using an active directory server. Here's what I've tried so far:</p>
  
  <pre><code>require 'rubygems'
  require 'net-ldap'
  
  host = '10.4.1.6'
  port = 389
  
  username = 'username'
  password = 'password'
  
  ldap = Net::LDAP.new
  ldap.host = host
  ldap.port = port
  ldap.auth "CN=#{username},CN=Users,DC=companyname,DC=ad", password
  
  if ldap.bind
    puts 'YES!'
    puts ldap.get_operation_result.message
  else
    puts 'NO :-('
    puts ldap.get_operation_result.message
  end
  </code></pre>
  
  <p>If I enter a non existing username and an empty string as a password, the bind operation succeeds. If I enter a valid username and a valid/invalid/empty password, the bind operation fails with error message 'Invalid Credentials'.</p>
  
  <p>I've looked at other threads and read the net-ldap documentation but I can't figure out what I'm doing wrong. </p>
  
  <p>Can someone give me some ideas on how to achieve this? </p>
  
  <p>Thanks in advance for any replies :-)</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>As @StuartEllis suggested, the problem was with the user identifier. To figure out the correct DN, I used the following script (taken from the net-ldap documentation):</p>
  
  <pre><code>ldap.auth "CN='adminUser',CN=Users,DC=companyname,DC=ad", 'adminUserPwd'
  ldap.bind
  treebase = "DC=companyname,DC=ad"
  filter = Net::LDAP::Filter.eq( "mail", "username@companyname.com" )
  attrs = ["mail", "cn", "sn","objectclass"]
  ldap.search( :base =&gt; treebase, :filter =&gt; filter, :attributes =&gt; attrs, :return_result =&gt; false ) do |entry|
    puts entry._dump 0
  end
  </code></pre>
  
  <p>I then retried using my original script (above) with the obtained DN and voila!</p>