Hi, Is there a Active Directory Helper Class available somewhere? Just checking before I re-invent the wheel.
I need to
Validate a user in AD.
Get hhis/her member roles.
Thanks
Hi, Is there a Active Directory Helper Class available somewhere? Just checking before I re-invent the wheel.
I need to
Validate a user in AD.
Get hhis/her member roles.
Thanks
System.DirectoryServices.ActiveDirectory namespace
http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectory.aspx
In .NET 3.5, you want to look in System.DirectoryServices.AccountManagement. For earlier, versions System.DirectoryServices has what you need, but it's a little more work.
using (var context = new PrincipalContext( ContextType.Domain ))
{
var valid = context.ValidateCredentials( username, password );
using (var user = UserPrincipal.FindByIdentity( context,
IdentityType.SamAccountName,
username ))
{
var groups = user.GetAuthorizationGroups();
}
}
Here is some example code that I have been using:
using System.DirectoryServices;
public static string GetProperty(SearchResult searchResult,
string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
return searchResult.Properties[PropertyName][0].ToString();
else
return string.Empty;
}
public MyCustomADRecord Login(string UserName, string Password)
{
string adPath = "LDAP://www.YourCompany.com/DC=YourCompany,DC=Com";
DirectorySearcher mySearcher;
SearchResult resEnt;
DirectoryEntry de = new DirectoryEntry(adPath, UserName, Password,
AuthenticationTypes.Secure);
mySearcher = new DirectorySearcher(de);
string adFilter = "(sAMAccountName=" + UserName + ")";
mySearcher.Filter = adFilter;
resEnt = mySearcher.FindOne();
return new MyCustomADRecord()
{
UserName = GetProperty(resEnt, "sAMAccountName"),
GUID = resEnt.GetDirectoryEntry().NativeGuid.ToString(),
DisplayName = GetProperty(resEnt, "displayName"),
FirstName = GetProperty(resEnt, "givenName"),
MiddleName = GetProperty(resEnt, "initials"),
LastName = GetProperty(resEnt, "sn"),
Company = GetProperty(resEnt, "company"),
JobTitle = GetProperty(resEnt, "title"),
Email = GetProperty(resEnt, "mail"),
Phone = GetProperty(resEnt, "telephoneNumber"),
ExtensionAttribute1 = GetProperty(resEnt, "extensionAttribute1")
};
}