Ruby LDAP Membership Query

01.20.2014 15:15 by kbeckman | Comments

Omniauth is easily one of the most often used Ruby gems in my toolset. Recently, I needed to use an Omniauth plugin that I haven’t used before – omniauth-ldap. Getting omniauth-ldap setup and configured was relatively straightforward; and as advertised, it provided authentication via LDAP query against the organization’s domain controller.

 

Unfortunately (and a bit unexpectedly) though, the contents of the Omniauth authentication hash didn’t contain a list of groups the user belonged to – a requirement for our authentication strategy. The applications I’m working need to translate a given user’s LDAP group membership(s) into application roles for authorization purposes. So as it turns out, after the initial LDAP call for authentication (via omniauth-ldap), I needed to make an additional query against the LDAP provider to get a list of the user’s memberships to parse and convert to application roles.

 

Here’s the short Ruby shell script I whipped up to test making an additional LDAP query for user memberships before I built a few classes and actually integrated it into the application. The @ldap_settings[:auth] hash are the account details used to connect and issue the LDAP query. The values of @ldap_settings and @base will change for your environment (I removed the actual values in this example).

 

#!/usr/bin/env ruby

require 'net/ldap'
require 'pry'

class MembershipQuery

  def initialize
    @ldap_settings = {
        :host => 'ldap-server',
        :auth => {
            :method   => :simple,
            :username => 'CN=Ldap Auth,OU=Authentication,OU=Service Accounts,DC=YOURDOMAIN',
            :password => 'password'
        }
    }

    @base = 'DC=YOURDOMAIN'
  end

  def query(username)
    result  = nil
    ldap    = Net::LDAP.new(@ldap_settings)
    filter  = "(&(objectClass=user)(sAMAccountName=#{username}))"

    if ldap.bind

      ldap.search(:base => @base, :filter => filter) do |object|
        result = object.memberof
      end
    else
      raise 'Authentication Error!'
    end

    result
  end

end

puts MembershipQuery.new().query('Ric_Flair')

Comments are Back!

01.20.2014 14:10 by kbeckman | Comments

I’ve had blog comments turned off for a some time now because this site has been hammered by comment SPAM bots. And admittedly, I got sick and tired of monitoring all of the garbage on a daily basis.

 

Today, I’m happy to announce that comments are back! I’ve wired up Disqus and thanks to a migration tool from Rob Ellison out on the West Coast, I was able to migrate all of the existing comments without having to spend any time parsing and transforming XML. If you notice any display issues or any other issues, please let me know…

I’m looking forward to hearing from you [again]…