使用net/ldap登录LDAP登录

Oma*_*Ali 4 authentication ldap ruby-on-rails

我试图让LDAP身份验证在Rails下工作.我选择了net/ldap,因为它是一个原生的Ruby LDAP库.

我已经尝试了所有可能的东西,特别是来自http://net-ldap.rubyforge.org/classes/Net/LDAP.html的例子,但仍然无法使其工作.有任何想法吗?

Oma*_*Ali 8

我设法达到的最佳解决方案是具有以下内容的模型:

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
Run Code Online (Sandbox Code Playgroud)


Dan*_*vin 5

我在使用LDAP进行身份验证的Rails 3 的Devise插件上工作,你可以查看源代码以获得一些想法,它目前使用net-ldap 0.1.1:

http://github.com/cschiewek/devise_ldap_authenticatable

LDAP服务器的实际连接和身份验证在以下位置完成:

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

最后,您可以查看我用于运行测试的示例LDAP服务器配置和Rails 3应用程序:

应用程序:http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/rails_app/

服务器:http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/ldap/