Access LDAP Server using Ruby

Dhepthi L Narasimhan

58 sec read

Recently I tried accessing LDAP server using ruby gem. I came to know about net-ldap gem which does the job in easier way. The Lightweight Directory Access Protocol (LDAP) is an application protocol for accessing and maintaining distributed directory information services over an Internet Protocol. Let’s see how to access information from LDAP using net-ldap gem.
1. First, Install the gem as

    [source language=”ruby”]
    gem install net-ldap
    [/source]

2. Initiate LDAP server as follows

    [source language=”ruby”]
    require ‘rubygems’
    require ‘net/ldap’
    ldap = Net::LDAP.new
    ldap.host = “x500.bund.de”
    ldap.port = “389”
    is_authorized = ldap.bind
    [/source]

x500.bund.de is public LDAP server. You can find various public ldap server in net.
3. If suppose we need to authenticate Ldap server using username and password. We can do it as

    [source language=”ruby”]
    ldap = Net::LDAP.new
    ldap.host = “x500.bund.de”
    ldap.port = “389”
    username = “xxxxxxxx”
    pasword = “xxxxxxxxx”
    ldap.auth username, password
    is_authorized = ldap.bind #returns true if auto works
    [/source]

4. Now let see how to search some records in LDAP server

    [source language=”ruby”]
    attrs = []
    ldap.search( :base => “l=init,ou=Service,o=Bund,c=DE”, :attributes => attrs, :return_result => true ) do |entry|
    # entry is records returned after search
    end
    [/source]
    Here entry will return set of records that matching the word given in base.

5. We can also use filter to refine our search as

    [source language=”ruby”]
    filter = Net::LDAP::Filter.eq(“username”, “xxxxx”)
    attrs = []
    ldap.search(:base => treebase, :filter => filter, :attributes => attrs,
    #refined search
    end
    [/source]

I hope this blog will be useful for accessing Ldap server using ruby gem. Any suggestion or comments are most welcome

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *