简体   繁体   中英

Authentication against Active Directory using C#

I am just having a user name and not having any password. I just want to check if this user name exist in Active Directory . How do I go about it?

If you're on .NET 3.5, you can use the System.DirectoryServices.AccountManagement features. Your code would look something like:

// create a "principal context" - e.g. your domain (could be machine, too)
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

UserPrincipal user = UserPrincipal.FindByIdentity(pc, "username");

bool userExists = (user != null);

That should do the trick ;-)

For more details on S.DS.AM, see this excellent MSDN article:

Managing Directory Security Principals in the .NET Framework 3.5

Try this:

string strDomain = DOMAINNAME;
string strUserId = USERNAME;

string strPath = "LDAP://DC=" + strDomain.Trim() + ",DC=com";

DirectoryEntry de = new DirectoryEntry(strPath);
DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + strUserId.Trim() + "))";

SearchResult results = deSearch.FindOne();
if ((results == null))
{
    //No User Found
}
else
{
   //User Found
}

You can use the class DirectoryEntry for such tasks. See the Exists -method here: http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.exists.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM