Ruby on Rails HTTP Basic Auth with LDAP
// December 8th, 2008 // Blog
My friend Fred has a nifty tip over on his Binary Fever blog about Ruby on Rails LDAP authentication using HTTP Basic Auth. I took what he had done and made a few minor improvements:
# mygeneric_controller.rb
LDAPBASE = ‘, ou=active, ou=employees, ou=people, o=host.com’
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic('LDAP Login') do |username, password|
ldap = Net::LDAP.new :host => ‘ldap.host.com’, :base => LDAPBASE
ldap.auth ‘uid=’ + username + LDAPBASE, password
if ldap.bind
@point_person = PointPerson.find_by_username(username)
if !@point_person.nil?
return true
end
else
return false
end
end
end




I’m not very good at this, but it seems your LDAPBASE could be:
LDAPBASE = ‘,ou=active…”
or your ldap.auth should be:
ldap.auth ‘uid=’ + username + ‘,’ +LDAPBASE
Of course, if works for you, maybe I’m wrong, but it seems you would get:
uid=ldap-uidou=active, ou=employee, ou=people, o=host.com
(no comma between ldap-uid and ou=active) with this example.
@gary is right just a typo on my code. dohp
Good catch @gary. I’ve updated the code.
Thank you for sharing this. I’m a beginner on Rails, so please understand if this is stupid.
I’m getting a “Invalid Credentials” message. Any idea?
Thanks
@Juan A few possibilities:
(1) You have not yet configured any users yet. Some LDAP records may be configured in such a way that only specific users can access the record (instead of binding anonymously). You may need to at least create a “manager” account as described in the OpenLDAP manual.
(2) The authentication mechanism used is incorrect. Say SASL is expected but you have used simple (password-based) authentication.
Patrick:
Thank you for your reply. I downloaded a little java app JXplorer to try to connect using my credentials, after changing the order of the cn property I was able to connect:
The proper order was:
ldap.auth ‘cn=’ + username + ‘,ou=active,ou=employees,ou=users,o=my_o’, password
Thank you again for the code and the reply. It is a success.
Thank you for share this code…
I’m having the following error:
uninitialized constant ApplicationController::PointPerson
at -> @point_person = PointPerson.find_by_username(username)
What can i do to solve it?
94man:
@point_person = PointPerson.find_by_username(username) is where we get the user to check against. You will want to replace this with your own user model.