4

I m using following code to check whether the provided parameters are correct or not for binding..

require 'rubygems'
require 'net/ldap'

ldap = Net::LDAP.new
ldap.host = your_server_ip_address
ldap.port = 389
ldap.auth "joe_user", "opensesame"
if ldap.bind
   # authentication succeeded
else
   # authentication failed
end

If user and password is incorrect it returns false but if host or port number is incorrect it displays error (exception)

 no connection to server (Net::LDAP::LdapError)

I want to capture this error also and want to show error msg separately for incoreect user/pass and for incorrect port/host name. How can i do this

Sonal S.
  • 1,444
  • 1
  • 15
  • 31
  • Probably too late for this post but you could wrap it in a begin, rescue block (see: https://ruby-doc.org/core-2.2.0/doc/syntax/exceptions_rdoc.html). – Mark Davies May 14 '18 at 14:17

1 Answers1

0

You can check all possible exceptions here: https://www.rubydoc.info/gems/net-ldap/Net/LDAP/Error

But some errors are not considered exceptions, so you have to get them with get_operation_result

ldap = Net::LDAP.new

begin
    ldap.host = '1.2.3.4'
    ldap.auth 'cn=config', 'myPassword'
    ldap.bind

rescue Net::LDAP::AuthMethodUnsupportedError => e
    puts "Net::LDAP::AuthMethodUnsupportedError: #{e}"

rescue Net::LDAP::BindingInformationInvalidError => e
    puts "Net::LDAP::BindingInformationInvalidError: #{e}"

rescue Net::LDAP::ConnectionError => e
    puts "Net::LDAP::ConnectionError: #{e}"

rescue Net::LDAP::ConnectionRefusedError => e
    puts "Net::LDAP::ConnectionRefusedError: #{e}"

rescue Net::LDAP::SocketError => e
    puts "Net::LDAP::SocketError: #{e}"

rescue StandardError => e
    # Timeout errors are rescued here
    puts "StandardError: #{e}"

end

# Wrong user/pass is not an exception and must be checked here
p ldap.get_operation_result
RASG
  • 5,988
  • 4
  • 26
  • 47