Check if user exists in Active Directory

偶尔善良 提交于 2020-01-04 01:51:09

问题


I am using vb.net and I want to check whether a particular user exists in Active Directory. If it does, I want to display the particular user's details. How to do it?

User login credentials are passed via textbox control

My code:

 Dim de As DirectoryEntry = GetDirectoryEntry()
 Dim ds As DirectorySearcher = New DirectorySearcher(de)
  ds.Filter = "(&(objectClass=txt1.text))"

    ' Use the FindAll method to return objects to SearchResultCollection.
    results = ds.FindAll()

Public Shared Function GetDirectoryEntry() As DirectoryEntry
    Dim dirEntry As DirectoryEntry = New DirectoryEntry()
    dirEntry.Path = "LDAP://ss.in:389/CN=Schema,CN=Configuration,DC=ss,DC=in"
    dirEntry.Username = "ss.in\ssldap"
    dirEntry.Password = "ss@123"
    'Dim searcher As New DirectorySearcher
    'searcher.SearchRoot = dirEntry
    Return dirEntry
End Function

Where I pass the password. Is this code is correct? I am new to AD. Pls help me to do this?


回答1:


If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // your user exists - do something here....      
}
else
{
   // your user in question does *not* exist - do something else....
} 

Or in VB.NET:

' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain)

' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, "SomeUserName")

If user IsNot Nothing Then
   ' your user exists - do something here....               
Else
   ' your user in question does *not* exist - do something else....
End If

The new S.DS.AM makes it really easy to play around with users and groups in AD!



来源:https://stackoverflow.com/questions/12722407/check-if-user-exists-in-active-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!