LDAP Authentication


#1

I have to do user authentication for a project i’m working on. The trick
is they want me to use the existing LDAP database for it. Does anyone
know how to authenticate using LDAP in RoR?

~Rahul


#2

From the RoR wiki:
http://wiki.rubyonrails.com/rails/pages/HowtoAuthenticateViaLdap

On 3/14/06, Rahul M. removed_email_address@domain.invalid wrote:


#3

And I hope you aren’t running the server on windows, cause I don’t
believe
Ruby-LDAP has been made to work there yet. =\


#4

I tried that method at first, but soon found ActiveLDAP does a few
extra things that slow it way down just for authentication. I pulled
out just the authentication code and found it much faster. Only need
Ruby LDAP installed.

Note :base and :bind_format must have your LDAP base. I have removed
non SSL connection attempts too.

require ‘ldap’
def self.ldap_config

end

def authenticate(username,password)
auth_config = {
# best if this is set in your environment
:host => “server.com”,
:port => 636,
:base => “#{your_base}”,
:bind_format => “userid=%s,#{your_base}”,
:allow_anonymous => false,
:user => username
}
auth_config[:port] ||= 636
auth_config[:retries] ||= 3
conn = nil
tries = 0
begin
# Connect to LDAP
begin
# SSL using START_TLS
conn = LDAP::SSLConn.new(auth_config[:host], auth_config
[:port], true)
rescue
begin
conn = LDAP::SSLConn.new(auth_config[:host], auth_config
[:port], false)
rescue
raise AuthenticationError, “All authentication mechanisms
failed”
end
end
# Enforce LDAPv3
conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)

   # Authenticate
   bind_dn = auth_config[:bind_format] % [auth_config[:user]]

   # Rough bind loop:
   # Attempt SASL
   auth = false
   begin
     auth = conn.bind(bind_dn, password)
   rescue
     return nil
   end

   unless auth
    raise AuthenticationError, "All authentication mechanisms

failed"
end
return auth
rescue => e
# Retry
tries += 1
raise e if tries > auth_config[:retries]
retry
end
end

I hope I didn’t cut too much out when removing my server info.

-John


John S.
Computing Staff - Webmaster
Kavli Institute for Theoretical Physics
University of California, Santa Barbara
removed_email_address@domain.invalid
(805) 893-6307