45

我一直在尝试将 Rails 应用程序连接到 ActiveDirectory。我将在 AD 和数据库之间同步有关用户的数据,目前是 MySQL(但可能会变成 SQL Server 或 PostgreSQL)。

我已经检查了 activedirectory-ruby,它看起来确实有问题(对于 1.0 版本!?)。它包装了 Net::LDAP,所以我尝试使用它,但它非常接近 LDAP 的实际语法,而且我喜欢 ActiveDirectory-Ruby 的抽象,因为它的语法类似于 ActiveRecord。

目录服务器是否有优雅的 ORM 类型工具?更好的是,如果有某种用于 LDAP 的脚手架工具(用于用户、组、组织单位等的 CRUD)。然后我可以通过 Authlogic 快速将其与我现有的身份验证代码集成,并保持所有数据同步。

4

6 回答 6

41

这是我与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.displayNamesome_entry['displayName'].

  • a 中的每个属性Net::LDAP::Entry始终是一个值数组,即使只有一个值存在。尽管让用户具有多个“displayName”值可能很愚蠢,但 LDAP 的通用性意味着它是可能的。最后的first调用将单字符串数组转换为用户全名的字符串。

于 2011-04-16T03:46:21.777 回答
4

这比真实的答案更轶事......

我在使用 Samba 和 OpenLDAP 服务器时也有类似的经历。我找不到真正做我想做的事的图书馆,所以我推出了自己的帮助类。

当我以“官方”方式创建用户时,我使用ldapbrowser查看 Samba 填写了哪些字段,并且基本上复制了该字段。

唯一棘手/非标准的 LDAP 是我们拥有的疯狂密码加密:

用户密码:

"{MD5}" + Base64.encode64(Digest::MD5.digest(pass))

sambaNT密码:

OpenSSL::Digest::MD4.hexdigest(Iconv.iconv("UCS-2", "UTF-8", pass).join).upcase

对于该def authenticate(user, pass)功能,我尝试使用他们的凭据让 LDAP 绑定到域,如果我发现异常则登录失败,否则让他们进入。

于 2008-12-22T20:43:20.950 回答
4

抱歉,还不能发表评论……也许有人可以适当地重新定位。

@Phrogz's solution works well, but bind_simple (inside bind) raises an Net::LDAP::LdapError exception due to auth[:username] not being set as shown here:

https://github.com/ruby-ldap/ruby-net-ldap/blob/master/lib/net/ldap.rb

The corrected replaces:

auth: { method: :simple, email: email, password:password }

with:

auth: { method: :simple, username: email, password:password }
于 2012-01-20T19:09:21.893 回答
2

我开始使用 ruby​​-activedirectory,甚至扩展/修复了一些东西,在 Github 中托管 judy-activedirectory。

在进行下一次迭代时,我发现 ActiveLdap 具有更好的代码库,我正在认真考虑切换到它。有没有人有这方面的亲身经历?

于 2009-02-04T21:16:03.030 回答
1

你检查过thinkbot 的ldap-activerecord-gateway 吗?这可能是你需要考虑的事情......

http://github.com/thoughtbot/ldap-activerecord-gateway/tree/master

于 2008-12-02T21:20:47.143 回答