Skip to content

Instantly share code, notes, and snippets.

@lpar
Created June 7, 2013 14:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lpar/5729836 to your computer and use it in GitHub Desktop.
Save lpar/5729836 to your computer and use it in GitHub Desktop.
Example of LDAP authentication in Ruby. Written for IBM Intranet, but should easily be adaptable to other environments.
#!/usr/bin/ruby
# An example of BluePages / IBM Intranet Password authentication using Ruby.
# Uses the gem ruby-ldap, a Ruby wrapper for OpenLDAP. Works with Ruby 2.0.
#
# To get this code to work, you must
#
# 1. gem install ruby-ldap
# 2. add
#
# TLS_REQCERT never
#
# to /etc/ldap/ldap.conf so that libopenssl doesn't demand a
# valid certificate.
require 'openssl'
require 'ldap'
require 'pp'
# The LDAP server to connect to
LDAP_SERVER = 'bluepages.ibm.com'
BASE_DN = 'ou=bluepages,o=ibm.com'
# The attributes to retrieve and return after successful authentication
LDAP_ATTRIBUTES = ['givenname','sn','mail','primaryuserid','uid']
# Perform an authentication check.
# username = Internet e-mail address
# password = IBM Intranet Password
# Uses SSL for the entire connection.
# Returns a hash of attributes if successful
# nil if unsuccessful
def intranetlogin(username, password)
# First step is to look up the DN and other attributes
ldap = LDAP::SSLConn.new(LDAP_SERVER, 636)
dn = ""
result = Hash.new
succeeded = ldap.search_ext(BASE_DN, LDAP::LDAP_SCOPE_SUBTREE,
"(&(objectClass=person)(mail=#{username}))") do |entry|
# Got an entry, so store the attributes
dn = entry.get_dn
# Must copy the entry the hard way, as it's a C object
for attr in LDAP_ATTRIBUTES
result[attr] = entry[attr]
end
end
if !succeeded or !dn
return nil
end
# Now perform the actual auth check by binding with the dn and password
ldap.unbind
if ldap.bind(dn, password)
return result
else
return nil
end
end
# An example of calling the code:
pp intranetlogin('johnsmith@us.ibm.com','password goes here')
@peterj35
Copy link

Superb, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment