Simple LDAP Authentication & Authorization in Ruby
For an application I’m currently writing I find myself needing to authenticate against my company Active Directory domain, now there’s a million authentication solutions out there for Rails but they’re all overkill and I’m using Ramaze for this anyway, so I decided to implement my own with Net::LDAP. I’m going to put the gist right here, and I’ll go over it in a moment
Now the code here is somewhat domain specific, but it’s fairly easy to adapt to other situations. Most directory configurations aren’t going to be simple enough where you can insert the username into a string to get the DN for binding (for example, my username is ‘snuxoll’ but my DN in Active Directory is CN=Stefan Nuxoll,CN=Users,DC=corp,DC=lithiumpc,DC=com) so you will need to search your directory to get the appropriate DN to authenticate against.
So let me go over some extremely basic usage
First we need to use find_user to retrieve the entry from the directory belonging to the user. From here we can call Net::LDAP::Entry#dn to get the distinguished name for the userĀ (e.g. CN=Stefan Nuxoll,CN=Users,DC=corp,DC=lithiumpc,DC=com), after that we will use authenticate_user to try to bind as the user with the specified password, lastly user_authorized? will check to see if the user belongs to the appropriate security group.
I’m sure this is probably as clear as mud to some people, I’m not really awake right now, but I wanted to share this code before I forget as some may find it useful.