Top Stories Photos on Yahoo! News Photos

Wednesday, August 20, 2008

Authenticate a User in Active Directory Using C#.NET

public user IsAuthenticated(string domainName, string userName, string password)
{
user userinformation = new user();
Result ReturnValue = new Result();
ReturnValue.ErrorCode = ErrorCode.UserAuthentication;


string FullName = domainName + @"\" + userName;
DirectoryEntry entry = new DirectoryEntry(this.ActiveDirectoryPath, FullName, password);
try
{
object AdEntry = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + userName + ")";
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne();

if (result == null)
{
ReturnValue.IsTrue = false;
ReturnValue.Message = "Unable to authenticate " + userName + ".";
userinformation.result = ReturnValue;
return userinformation;
}

this.ActiveDirectoryPath = result.Path;

ReturnValue.IsTrue = true;
ReturnValue.Message = "Welecome " + userName + ".";
ReturnValue.UserName = (string)result.Properties["cn"][0];

userinformation.Username = ReturnValue.UserName;
userinformation.LogonUserName = userName;
if (result.Properties["mail"].Count > 0)
userinformation.Email = (string)result.Properties["mail"][0];
else
userinformation.Email = "no-email@domain.com";

}
catch (Exception ex)
{
ReturnValue.IsTrue = false;
ReturnValue.Message = ex.Message;
ReturnValue.Exception = ex.Message;
}

userinformation.result = ReturnValue;

return userinformation;
}

No comments: