Sarav's Weblog

Technical Articles for RoR Developers

Tag Archives: ruby ldap connection

Ruby-LDAP (add, search)

LDAP in Ruby

To use LDAP in Ruby you have to use following gems. So Install the following gems.

  • sudo gem install net-ldap
  • sudo gem insall ruby-net-ldap

User Authentication against LDAP Directory Using Ruby

Example of a user-authentication against an LDAP directory:

require 'rubygems'
require 'net/ldap'

ldap = Net::LDAP.new
ldap.host = your_server_ip_address
ldap.port = 389
ldap.auth "joe_user", "opensesame"
if ldap.bind
  # authentication succeeded
else
  # authentication failed
end

Search against LDAP Directory Using Ruby

Quick Example of a search against an LDAP directory:

require 'rubygems'
require 'net/ldap'

username = "cn=manager,dc=example,dc=com"
password = "xxxxxxxx"
host = example.com #(or) host = 111.111.111.11 (ipaddress)
ldap = Net::LDAP.new :host => host,  :port => 389
ldap.auth username, password

filter = Net::LDAP::Filter.eq( "cn", "George*" )
treebase = "dc=example,dc=com"

ldap.search( :base => treebase, :filter => filter ) do |entry|
  puts "DN: #{entry.dn}"
  entry.each do |attribute, values|
    puts "   #{attribute}:"
    values.each do |value|
      puts "      --->#{value}"
    end
  end
end

#puts  ldap.get_operation_result

Check out the rest of the documentation for pretty good examples. This is the library I recommend. In my situation, I’m using ruby-net-ldap to import data in to, manipulate and query data in an OpenDS LDAP server.