简体   繁体   中英

Using Ruby Webrick HTTPAuth with LDAP

The app I am writing has the ability to have a login popup appear and it authenticates against a hard coded username/password constant pair. I would like to authenticate against our central LDAP server. the we dont have a base however we do have a bind_dn string of "cn=USERFOO,ou=it,o=corporate". The variables user/pass are passed in through the basic login box.

I am trying to do this through ActiveLdap however I dont mind using any other library as long as I can validate the credentials through a single sign on against our LDAP server using the HTTPAuth since is written completely in Webrick Ruby. Below is a sample of the function I am calling. Does anyone have any idea how to do this? Thanks in advance.

def authenticate_ldap(req,res)
    authlabel = "LDAP Authentication"
    HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
      ActiveLdap::Base.setup_connection(
        :host => 'ldap.internalserver.com',
        :port => 389,
        :bind_dn => "cn=#{user},ou=it,o=corporate",
        :password_block => Proc.new { pass },
      )
    }
    return
end

I figured out a solution. The person who manages our LDAP server provided the incorrect ldap connection string, but even with that it still didn't work.

The solution I discovered that did indeed make a connection with very basic validation is something to this effect for anyone else interested in a very simple ldap authentication popup in pure Ruby.

def authenticate(req,res)
  authlabel = 'LDAP Authentication'
  HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
    if pass.to_s != ''
      ldap = Net::LDAP.new
      ldap.host = "ldap.serverfoo.com"
      ldap.port = 389
      result = ldap.bind_as(
          :base => "t=basetreefoo",
          :filter => "uid=#{user}",
          :password => pass
      )
      if result
        ldap = Net::LDAP.new  :host => "ldap.serverfoo.com",
                              :port => "389",
                              :auth => {
                                  :method => :simple,
                                  :username => "", 
                                  :password => "" 
                              }

        group_name = Net::LDAP::Filter.eq("cn", "#{user}")
        group_type = Net::LDAP::Filter.eq("groupmembership", "cn=infra,ou=IT,o=Corporate")
        filter = group_name & group_type
        treebase = "t=basetreefoo"
        ldap.search(:base => treebase, :filter => filter) do |entry|
          if entry.dn.to_s != ""
            puts 'success'
            return
          end
        end
      end
    end
    puts 'fail'
  }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM