Showing posts with label Active Directory. Show all posts
Showing posts with label Active Directory. Show all posts

Friday, April 4, 2008

interacting with Active Directory


Recently I had to work on a web application that authenticated via Active Directory/IIS. In other words in IIS, anonymous access was turned off for my app, and Windows Authentication was turned on (image shows default setting for a web app; for this situation you need to uncheck anonymous access and check windows integration). When you do this, you then set at the folder level in Windows explorer who has access. It is at the folder level that it was indicated, in my case, to use Active Directory. For the current ePortfolio, on the other hand, users were added, account by account, to the folder via the Security tab.


Here are some articles on the topic:

Integrated Security with Web Application

Accessing the Active Directory from Microsoft .NET

Howto: (Almost) Everything In Active Directory via C#

Now I didn't really use the methods describes in these articles because they all demonstrate a way to interact with Active Directory that involves connecting directly to the Active Directory server. In my situation, I was not able to obtain the information needed to create the connection (LDAP server info). So below I will show you the code I did use.


string strADUser = Request.ServerVariables["LOGON_USER"].ToString().Substring(Request.ServerVariables["LOGON_USER"].ToString().LastIndexOf("\\") + 1);


Note that for ePortfolio Dave accessed the "HttpContext.Current.User.Identity.Name" property. I tried this first but it appears AD does not populate this property.

The last of my code:

Here I compare the SAMAccountName of the logged in user, to see if that person is a member of a specific AD group:


DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", strADUser);
search.PropertiesToLoad.Add("memberOf");

SearchResult result = search.FindOne();
if (result != null)
{
int groupCount = result.Properties["memberOf"].Count;

for (int counter = 0; counter < groupCount; counter++)
{
string str = (string)result.Properties["memberOf"][counter];
if (str.Contains(editGroupName))
{
return true;
}
}
}


Any questions, suggestions for improvement? Post to the comments!