How to Ruby on Rails authentication with LDAP? [cl

2020-05-07 19:28发布

I'm developing a web app and I have an authentication method using bcrypt gemIt works fine, but I wanted to change the authentication method to LDAP because I'm using an intranet environment and want my users to be able to sign in with windows credentials.

I'm looking to use net-ldap gem but I can't find any good toturials/explanations online on how to implement this into my web application.

  • Can you help me with this?
  • How can I do this?

2条回答
对你真心纯属浪费
2楼-- · 2020-05-07 19:54

Here's a utility class I've used in the past to do multi-server LDAP check:

require 'net/ldap'

# Ldap.authenticate('user', 'password')
# => `true` if valid
# => `false` if invalid
# => `nil` if LDAP unavailable

class Ldap
  def self.config
    {
      domain: 'mydomain',
      servers: ['server1', 'server2']
    }
  end

  def self.authenticate(login, pass)
    return false if login.empty? or pass.empty?
    config['servers'].each do |server|
      auth = authenticate_against_server(login, pass, server, config['domain'])
      return auth unless auth.nil?
    end
    nil
  end

 private

  def self.authenticate_against_server(login, pass, host, domain)
    conn = Net::LDAP.new(
      host:       host,
      port:       636,
      base:       "dc=#{domain}, dc=local",
      encryption: :simple_tls,
      auth:       { username: "#{login}@#{domain}.local",
                    password: pass,
                    method: :simple }
    )
    Timeout::timeout(15) do
      return conn.bind ? true : false
    end
  rescue Net::LDAP::LdapError => e
    notify_ldap_admin(host, 'Error', e)
    return nil
  rescue Timeout::Error => e
    notify_ldap_admin(host, 'Timeout', e)
    return nil
  end

  def self.notify_ldap_admin(host, error_type, error)
    msg = "LDAP #{error_type} on #{host}"
    RAILS_DEFAULT_LOGGER.debug(msg)
    DeveloperMailer.deliver_ldap_failure_msg(msg, error)
  end
end
查看更多
爷的心禁止访问
3楼-- · 2020-05-07 20:01

If you're fairly new, I'd avoid homebrewing authentication. Check out either

I started with Devise, and still use it for a few projects, but Omniauth is super powerful and more versatile in my opinion. You have to do more yourself though.

Further reading should include CanCanCan for authorization within your app, unless everybody gets everything that is.

查看更多
登录 后发表回答