ruby-on-rails - 通过 Ruby 或 Rails 的 LDAP

标签 ruby-on-rails ruby active-directory ldap

我一直在尝试将 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.displayNamesome_entry['displayName'] 相同。

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

关于ruby-on-rails - 通过 Ruby 或 Rails 的 LDAP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/334519/

相关文章:

windows - 允许外部用户与内部服务通信

ruby-on-rails - 对每个用户的Rails中的函数调用进行速率限制

ruby-on-rails - 您如何在本地网络上托管 Ruby on Rails 应用程序,以便多人可以访问它?

ruby - 如果代码块评估为 false,则跳过 enumerable#map 上的值

.net - Powershell GUI - 是否有用于选择 OU 的 Active Directory 对话框?喜欢 FileOpenDialog?

powershell - 密码过期前的天数

ruby-on-rails - 更新模型属性

ruby-on-rails - 发现 Invalid Record factory girl 中的错误

ruby - 无法在 OSX 上安装 gem mysql

ruby - Array#first 的 block 参数有什么作用?