开发者

How to check for user credentials using active directory and a ruby script

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:

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

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'.

开发者_C百科

I've looked at other threads and read the net-ldap documentation but I can't figure out what I'm doing wrong.

Can someone give me some ideas on how to achieve this?

Thanks in advance for any replies :-)

Edit:

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):

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 => treebase, :filter => filter, :attributes => attrs, :return_result => false ) do |entry|
  puts entry._dump 0
end

I then retried using my original script (above) with the obtained DN and voila!


I would guess that your LDAP account details aren't correct, but your LDAP server accepts anonymous binds, which is why it works when you don't specify a valid username and password. LDAP user identifiers are very fiddly, so I'd suggest double-checking the whole thing, including the case of the parts.


Here is sample code I use with the net-ldap gem to verify user logins from the ActiveDirectory server at my work:

def name_for_login( email, password )
  email = email[/\A\w+/].downcase  # Throw out the domain, if it was there
  email << "@mycompany.com"        # I only check people in my company
  ldap = Net::LDAP.new(
    host: 'ldap.mycompany.com',    # Thankfully this is a standard name
    auth: { method: :simple, email: email, password:password }
  )
  if ldap.bind
    # Yay, the login credentials were valid!
    # Get the user's full name and return it
    ldap.search(
      base:         "OU=Users,OU=Accounts,DC=mycompany,DC=com",
      filter:       Net::LDAP::Filter.eq( "mail", email ),
      attributes:   %w[ displayName ],
      return_result:true
    ).first.displayName.first
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜