Search

Friday, October 12, 2007

Get a User's Primary Group Membership from Active Directory with ColdFusion

Recently, I've had to do much work with Active Directory/LDAP. I needed a way to grab the user's primary group so I can set some permissions in my application based on the primary group the user is a member of. This turned out to be a bit tricky since the primary group for each user is not part of the list of groups the user is a member of. Instead, the primary group token (just an ID) is stored in each user's record. Seems pretty simple now that I got it working but there was a big lack of documentation on how to do this in ColdFusion. So here is the psudo code:
  1. We need to query Active Directory and get the value of the "primaryGroupID" for the selected user
  2. We also need a full list of groups in Active Directory (this is acheived with using the filter "(&(objectcategory=group))")
  3. Next, we need to get the group name from the full list of groups based on the primary group token we got from the user's record
  4. Bingo!
Here is the code:
<!--- Get the primary group id for an example user --->
<cfldap
	action="query"
	name="userLdapQuery"
	start="dc=ica,dc=com"
	server="ldapServer"
	username="ldapUser"
	password="secretPassword"
	scope="subtree"
	filter="sAMAccountName=bkostadinov"
	attributes="primaryGroupID"
	timeout="0"
	maxrows="1" />

<!--- Query the ldap server for the full list of groups --->
<cfldap
	action="query"
	name="groupsQuery"
	start="dc=ica,dc=com"
	server="ldapServer"
	username="ldapUser"
	password="secretPassword"
	scope="subtree"
	filter="(&(objectcategory=group))"
	attributes="primaryGroupToken,name"
	timeout="0" />

<!--- Beacause the list of groups the user belongs to,
does not contain the user's primary group, query the
ldap groups to get only the group name for witch
the value of the primaryGroupTokenAttribute
matches the value of the primaryGroupIDAttribute --->
<cfquery name="primaryGroupQuery" dbtype="query">
select	lower(name) as name
from	groupsQuery
where	primaryGroupToken = '#userLdapQuery.primaryGroupID#'
</cfquery>

<!--- Get the primary group name from the query resutls --->
<cfset primaryGroup = primaryGroupQuery["name"][1] />
// //]]>