Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
LDAP | 125

development:
host:(ldap server name)
port: 389
base:dc=mycompany,dc=com
password:my_password

production:
...

Then, at the bottom ofconfig/environment.rb, set up the connection:


ldap_path = File.join(RAILS_ROOT,"config","ldap.yml")
ldap_config = YAML.load(File.read(ldap_path))[RAILS_ENV]
ActiveLDAP::Base.establish_connection(ldap_config)

To set up ActiveLDAP, just subclassActiveLDAP::Baseand set the LDA Pmapping on
a class-by-class basis:


class Employee < ActiveLDAP::Base
ldap_mapping :prefix => "ou=Employees"
end

LDAP queries can then be executed using the class methods onActiveLDAP::Base:


@dan = Employee.find :attribute => "cn", :value => "Dan"

Authenticating with LDAP


One of the most common reasons for using LDA Pis to integrate into an existing
authentication structure. If an LDA Pserver is provided for a Windows domain, this
will allow the web application to authenticate users against that domain rather than
maintaining its own user models separately.


Set up theldap.ymlfile as described previously (without specifying a password), but
do not bind to the LDA Pserver fromenvironment.rb. We will perform the bind as
part of the authentication process. The following code is adapted from the Rails wiki:*


class LdapUser < ActiveLDAP::Base
ldap_mapping :prefix =>(LDAP prefix for your users)

LDAP_PATH = File.join(RAILS_ROOT,"config","ldap.yml")
LDAP_CONFIG = YAML.load(File.read(ldap_path))[RAILS_ENV]

def self.authenticate username, password
begin
ActiveLDAP::Base.establish_connection(config.merge(
:bind_format => "uid=#{username},cn=users,dc=mycompany,dc=com",
:password => password,
:allow_anonymous => false
))
ActiveLDAP::Base.close
return true

*http://wiki.rubyonrails.org/rails/pages/HowtoAuthenticateViaLdap

Free download pdf