Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails LDAP login using net/ldap

I am trying to get LDAP authentication to work under Rails. I have chosen net/ldap since it's a native Ruby LDAP library.

I have tried all possible stuff, specially examples from http://net-ldap.rubyforge.org/classes/Net/LDAP.html but still unable to get it work. Any ideas?

like image 577
Omar Ali Avatar asked Dec 12 '22 20:12

Omar Ali


2 Answers

The best solution I managed to reach is a Model with the following:

require 'net/ldap'

class User < ActiveRecord::Base

  def after_initialize
    @config = YAML.load(ERB.new(File.read("#{Rails.root}/config/ldap.yml")).result)[Rails.env]
  end

  def ldap_auth(user, pass)
    ldap = initialize_ldap_con
    result = ldap.bind_as(
      :base => @config['base_dn'],
      :filter => "(#{@config['attributes']['id']}=#{user})",
      :password => pass
    )
    if result
      # fetch user DN
      get_user_dn user
      sync_ldap_with_db user
    end
    nil
  end

  private
  def initialize_ldap_con
    options = { :host => @config['host'],
                :port => @config['port'],
                :encryption => (@config['tls'] ? :simple_tls : nil),
                :auth => { 
                  :method => :simple,
                  :username => @config['ldap_user'],
                  :password => @config['ldap_password']
                }
              }
    Net::LDAP.new options
  end

  def get_user_dn(user)
    ldap = initialize_ldap_con
    login_filter = Net::LDAP::Filter.eq @config['attributes']['id'], "#{user}"
    object_filter = Net::LDAP::Filter.eq "objectClass", "*" 

    ldap.search :base => @config['base_dn'],
                :filter => object_filter & login_filter,
                :attributes => ['dn', @config['attributes']['first_name'], @config['attributes']['last_name'], @config['attributes']['mail']] do |entry|
      logger.debug "DN: #{entry.dn}"
      entry.each do |attr, values|
        values.each do |value|
          logger.debug "#{attr} = #{value}"
        end
      end
    end
  end
end
like image 193
Omar Ali Avatar answered Dec 26 '22 20:12

Omar Ali


I work on a Devise plugin for Rails 3 that uses LDAP for authentication, you can look at the source to get some ideas, it currently uses net-ldap 0.1.1:

http://github.com/cschiewek/devise_ldap_authenticatable

The actual connecting and authenticating to the LDAP sever is done at:

http://github.com/cschiewek/devise_ldap_authenticatable/blob/master/lib/devise_ldap_authenticatable/ldap_adapter.rb

Lastly, you can look at the sample LDAP server config and Rails 3 app I use to run the tests against:

App: http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/rails_app/

Server: http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/ldap/

like image 39
Dan McNevin Avatar answered Dec 26 '22 20:12

Dan McNevin