我一直在尝试将 Rails 应用程序连接到 ActiveDirectory。我将在 AD 和数据库之间同步有关用户的数据,目前是 MySQL(但可能会变成 SQL Server 或 PostgreSQL)。
我检查了 activedirectory-ruby,它看起来确实有问题(对于 1.0 版本!?)。它包装了 Net::LDAP,所以我尝试使用它,但它非常接近 LDAP 的实际语法,而且我喜欢 ActiveDirectory-Ruby 的抽象,因为它有类似 ActiveRecord 的语法。
是否有用于目录服务器的优雅的 ORM 类型工具?更好的是,如果有某种 LDAP 脚手架工具(用于用户、组、组织单位等的 CRUD)。然后我可以通过 Authlogic 快速将其与我现有的身份验证代码集成,并保持所有数据同步。
最佳答案
这是我在 net-ldap 中使用的示例代码gem 在我的工作中从 ActiveDirectory 服务器验证用户登录:
require 'net/ldap' # gem install net-ldap
def name_for_login( email, password )
email = email[/\A\w+/].downcase # Throw out the domain, if it was there
email << "@mycompany.com" # I only check people in my company
ldap = Net::LDAP.new(
host: 'ldap.mycompany.com', # Thankfully this is a standard name
auth: { method: :simple, email: email, password:password }
)
if ldap.bind
# Yay, the login credentials were valid!
# Get the user's full name and return it
ldap.search(
base: "OU=Users,OU=Accounts,DC=mycompany,DC=com",
filter: Net::LDAP::Filter.eq( "mail", email ),
attributes: %w[ displayName ],
return_result:true
).first.displayName.first
end
end
最后的 first.displayName.first
代码看起来有点傻,所以可能需要一些解释:
Net::LDAP#search
始终返回一组结果,即使您最终只匹配了一个条目。第一次调用first
会找到与电子邮件地址匹配的第一个(并且可能是唯一的)条目。Net::LDAP::Entry
搜索返回的内容方便您通过方法名称访问属性,因此some_entry.displayName
与some_entry['displayName']
相同。Net::LDAP::Entry
中的每个属性始终是一组值,即使只有一个值存在。虽然让一个用户具有多个“displayName”值可能很愚蠢,但 LDAP 的通用性质意味着这是可能的。最后的first
调用将单字符串数组转换为用户全名的字符串。
关于ruby-on-rails - 通过 Ruby 或 Rails 的 LDAP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/334519/