Following sample code shows how Rails integrates with Microsoft Active Directory using net-ldap gem.
Active Directory Environment: Windows Server 2012 R2
Development Environment: CentOS 7.5
Rails Version: 5.2.0
Create a Rails application
rails new ldap_example
Since I use PostgreSQL instead of sqlite3, I got following error:
An error occurred while installing sqlite3 (1.3.13), and Bundler cannot continue.
Make sure that `gem install sqlite3 -v '1.3.13'` succeeds before bundling.
Therefore, I use –with-pg-config option to use PostgreSQL.
rails new ldap_example --skip-spring --skip-turbolinks --skip-test-unit --with-pg-config=/usr/bin/pg_config --database=postgresql
Add net-ldap to the Gemfile
# Net::LDAP
gem 'net-ldap'
Install net-ldap
bundle install
Create a controller
rails generate controller sessions
Connect to your AD
class SessionsController < ApplicationController
def login
ldap = Net::LDAP.new :host => '10.1.33.16',
:port => '389',
:auth => {
:method => :simple,
:username => "cywang@mydomain.com",
:password => "tEsTpAsSwOrD1234"
}
if ldap.bind
render json: {'Result': 'Login Succeeded!'}, status: status
else
render json: {'Result': 'Login failed'}, status: status
end
end
end
You can simply change the password or username to test your login method.