使用net / LDAP Rails的LDAP登录 [英] Rails LDAP login using net/ldap
本文介绍了使用net / LDAP Rails的LDAP登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得LDAP身份验证下Rails的工作。
我选择了网/ 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特别的例子://网络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屋!
查看全文