Neo
Neo

Reputation: 349

Rails authentication with LDAP

I am learning Rails(no experience in web development and MVC), and to improve my skills, wanted to implement an application where authentication is done in LDAP. I have been reading RAILS 4 IN ACTION by Ryan Bigg and RUBY ON RAILS TUTORIAL by Michael Hartl. Now in those tutorials, applications that are developed needs an authentication system. They build the authentication system from scratch. Since the username/passwords are saved in the database they generate a User model. My question is, if I save user data in LDAP(and do authentication via LDAP), do I need to generate a user model? The User model is also used for saving cookies(to remember user sessions). Does it mean that I should generate User model but only save session data? Any pointer would be appreciated.

Upvotes: 2

Views: 7239

Answers (1)

adamliesko
adamliesko

Reputation: 1915

You certainly do not need to create a model inheriting from ActiveRecord::Base class, but having some class to hold the user information is suitable - even if it is only for the duration of a run time. Or do you really only wanto to do the authentication and then forget about the user?

If you are interested in using LDAP with the de facto standard Rails gem for authentication - devise , take a look at this Wiki Page https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP.

All you have to do, is just use custom authentification strategy.

require 'net/ldap'
require 'devise/strategies/authenticatable'

module Devise
  module Strategies
    class LdapAuthenticatable < Authenticatable
      def authenticate!
        if params[:user]
          ldap = Net::LDAP.new
          ldap.host = [YOUR LDAP HOSTNAME]
          ldap.port = [YOUR LDAP HOSTNAME PORT]
          ldap.auth email, password

          if ldap.bind
            user = User.find_or_create_by(email: email) #optional lookup
            success!(user) # you do have to return some object
          else
            fail(:invalid_login)
          end
        end
      end

      def email
        params[:user][:email]
      end

      def password
        params[:user][:password]
      end

    end
  end
end

Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)

If you want to avoid using devise go for warden-ldap https://github.com/renewablefunding/warden-ldap.

Upvotes: 2

Related Questions