使用 net/ldap 登录 Rails LDAP [英] Rails LDAP login using net/ldap

查看:21
本文介绍了使用 net/ldap 登录 Rails LDAP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 LDAP 身份验证在 Rails 下工作.我选择了 net/ldap,因为它是一个原生 Ruby 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.

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

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?

推荐答案

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

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

这篇关于使用 net/ldap 登录 Rails LDAP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆