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