Friday, February 15, 2008

Use Active Directory to Authenticate

Today I spent sometime to review the System.DirectoryServices name space in .Net 2.0. It is very convenient to use it to access A.D. and doing Authentication for your apps. Here are some sample codes in C# you might need to start with:

//Variables for getting groups
string _path;
string _filterAttr;

bool validateUser(string username, string password)
{
//Validate Users
string path = "LDAP:// your domain";
string domainUserName = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(path, domainUserName, password);

try
{
// Bind to the native object to force authentication to happen
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
// Authenticated
_path = result.Path;
_filterAttr = result.Properties["cn"][0].ToString();
return true;
}
else
return false;
}
catch (Exception ex)
{
throw new Exception("User not authenticated: " + ex.Message);
}
}

//Getting the groups this user belongs to
string getUserGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttr + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groups = new StringBuilder();

try
{
SearchResult result = search.FindOne();

int nCnt = result.Properties["memberOf"].Count;

for (int i = 0; i < nCnt; i++)
{
string dn = result.Properties["memberOf"][i].ToString();
int eidx = dn.IndexOf("=", 1);
int cidx = dn.IndexOf(",", 1);

if (eidx == -1)
{
return string.Empty;
}

groups.Append(dn.Substring(eidx + 1, cidx - eidx - 1));
groups.Append("|");
}
}
catch(Exception ex)
{
throw new Exception("Groups not getting: " + ex.Message);
}
return groups.ToString();
}

No comments: