ruby
  1. ruby-ldap

Ruby LDAP

LDAP stands for Lightweight Directory Access Protocol, which is a protocol used for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network. In Ruby, the Net::LDAP module provides support for accessing an LDAP server.

Syntax

To connect to the LDAP server:

require 'net/ldap'
ldap = Net::LDAP.new(:host => 'ldap.example.com', :port => 389)

To bind to the LDAP server with a username and password:

ldap.auth('username', 'password')

To search for a user:

ldap.search(:base => 'ou=People,dc=example,dc=com', :filter => Net::LDAP::Filter.eq('uid', 'user123')) do |entry|
  # Do something with the user's entry
end

Example

Here is an example of how to authenticate a user against an LDAP server using Ruby:

require 'net/ldap'

ldap = Net::LDAP.new(
  host: 'ldap.example.com',
  port: 389,
  auth: {
    method: :simple,
    username: 'user123',
    password: 'password'
  }
)

if ldap.bind
  puts "Authenticated successfully"
else
  puts "Authentication failed"
end

Output

The output of the example above will be either "Authenticated successfully" or "Authentication failed" depending on whether or not the LDAP server authenticated the provided username and password.

Explanation

In the example above, we first create a Net::LDAP object with the host and port of the LDAP server we want to connect to, as well as the username and password for authenticating.

We then call the bind method on the LDAP object, which attempts to authenticate against the LDAP server using the provided credentials. If the bind succeeds, the method returns true, indicating that the authentication was successful. Otherwise, it returns false, indicating that the authentication failed.

Use

Ruby LDAP is commonly used in web applications to authenticate users against an LDAP server. It can also be used for adding, deleting, and modifying entries in an LDAP directory.

Important Points

  • The Net::LDAP module is included in Ruby's standard library, so no additional gems or installations are necessary.
  • When searching for entries in an LDAP directory, you can specify the base DN (distinguished name) of the directory and a search filter to narrow down the results.
  • There are various authentication methods that can be used with Net::LDAP, including simple bind, GSSAPI, and SASL.

Summary

Ruby LDAP provides a simple and efficient way to connect to and authenticate against an LDAP directory server. With its robust search and authentication capabilities, it is a valuable tool for any web application that needs to work with LDAP.

Published on: