Rails rails 中实现 windows 集成认证

carl · 2012年02月12日 · 最后由 lyfi2003 回复于 2012年02月12日 · 4082 次阅读

如题,rails 中可以实现 windows 集成认证吗(windows 环境下)?大家有研究过的吗?如果一个 rails 项目想实现 windows 集成认证,要怎么做呢?谢谢!

或者说 rail 中怎么做 LDAP 集成认证呢?

用 ruby-ldap 这个 gem

然后,大概的代码如下,然后就跟密码认证差不多了:

require 'ldap'

conn = LDAP::Conn.new( '<domain-server>', 389 )
conn.set_option( LDAP::LDAP_OPT_PROTOCOL_VERSION, 3 )
conn.bind( '<domain>\<username>', '<password>' ) do |conn|

base = 'ou=Users,ou=<container>,dc=<domain>,dc=local'

results = conn.search2(base, LDAP::LDAP_SCOPE_SUBTREE, '(cn=*)')
results.each { |entry| puts "#{entry['dn']}: #{entry['telephoneNumber']}" }

end

或者用这个 gem: net-ldap 参考: http://stackoverflow.com/questions/3539501/rails-ldap-login-using-net-ldap

#1 楼 @lyfi2003 就是说还是需要用户输入账号密码的?然后这个账号密码传到我们服务器的后台再与 LDAP 做验证?我想要的是那种类似于 windows 集成认证的,就是在一个公司的网络环境中,大家可以通过集成认证访问我们的网站,但是我们的网站不会得到用户的任何信息,尤其是密码?是这种吗?谢谢!

Rails 肯定要知道相关密码 (也许是加密后的),然后传给 LDAP 作认证,通过了 rails 就可以认为 OK 了,创建好 session 的登录信息就可以了。 可以参考以下的 model:( 来自 stackoverflow )

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

#3 楼 @lyfi2003 哦,明白。那 ruby on rails 可以实现 windows AD 认证吗?windows AD 认证和这个有区别吗?也必须要我们程序的后台知道账号、密码然后去做验证?没有那种类似于 OAuth 认证的,可以不用告诉我们密码然后自己去做认证的?

从原理上讲是必须要知道的,因为 rails 只是一 web 表现层,无法获取 ntlm 认证信息。而且必须能够查询到 AD. 除非除非你设计一个浏览器插件,用来获取本地的认证域信息。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号