Adding User to AD Group in VB.Net (2008) - vb.net

I needed to add users to Active Directory using VB. I found code that works (mostly), except for assigning the user to a group. I'm fairly certain that the code works, I just don't know the format of the group to pass to it.
Given the code (below), and the image of my AD structure (below that), what is the structure of the GroupName passed to the routine to add the user to the group "Level1/All Users/Level 2/A-K"?
TIA
Public Shared Sub AddUserToGroup(ByVal de As DirectoryEntry, ByVal deUser As DirectoryEntry, ByVal GroupName As String)
Dim deSearch As DirectorySearcher = New DirectorySearcher()
deSearch.SearchRoot = de
deSearch.Filter = "(&(objectClass=group) (cn=" & GroupName & "))"
Dim results As SearchResultCollection = deSearch.FindAll()
Dim isGroupMember As Boolean = False
If results.Count > 0 Then
Dim group As New DirectoryEntry(results(0).Path)
Dim members As Object = group.Invoke("Members", Nothing)
For Each member As Object In CType(members, IEnumerable)
Dim x As DirectoryEntry = New DirectoryEntry(member)
Dim name As String = x.Name
If name <> deUser.Name Then
isGroupMember = False
Else
isGroupMember = True
Exit For
End If
Next member
If (Not isGroupMember) Then
group.Invoke("Add", New Object() {deUser.Path.ToString()})
End If
group.Close()
End If
Return
End Sub

According to your input from your comment I set up this Sub for you.
You havn't clarified the level below Level2 so I just called it Level3.
This function already enables User as a disabled User is useless...
References:
Imports System.DirectoryServices
How to Use:
CreateUser("Doe", "John")
Method:
Public Sub CreateUser(ByVal givenname As String, ByVal surname As String)
Dim dom As New DirectoryEntry()
Dim ou As DirectoryEntry = dom.Children.Find("OU=All Users")
Dim ou2 As DirectoryEntry = ou.Children.Find("OU=Level2")
Dim ou3 As DirectoryEntry = ou2.Children.Find("OU=Level3")
Dim firstLetter As String = givenname.Substring(0, 1)
Dim ou4 As DirectoryEntry
If firstLetter Like "*[A-K]*" Then
ou4 = ou3.Children.Find("OU=A-K")
Else
ou4 = ou3.Children.Find("OU=L-Z")
End If
Dim ADuser As DirectoryEntry = ou4.Children.Add("CN=" & givenname & "\, " & surname, "user")
ADuser.CommitChanges()
'The User is now created. Most people forget to enable their users so I'll put it in here too
'UF_DONT_EXPIRE_PASSWD 0x10000
Dim exp As Integer = CInt(ADuser.Properties("userAccountControl").Value)
ADuser.Properties("userAccountControl").Value = exp Or &H1
ADuser.CommitChanges()
'UF_ACCOUNTDISABLE 0x0002
Dim val As Integer = CInt(ADuser.Properties("userAccountControl").Value)
ADuser.Properties("userAccountControl").Value = val And Not &H2
ADuser.CommitChanges()
End Sub
See my answer in this post for basic knowledge of interaction with AD and LDAP.

Related

checking login credentials to see if they are valid in Active Directory AND check to see if they are apart of a specific group in AD

below is a method used to check to see if the Creds entered are good. i also would like to add on to this to see if they are part of group "XXX".
Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim Success As Boolean = False
Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" + Domain, Username, Password)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Try
Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Results Is Nothing)
Catch ex As Exception
Success = False
End Try
Return Success
End Function
and below i tried to play around with stuff i found on stack but im not having much luck. how can i use existing method and add to it in order to get my results?
Public Function IsInGroup(ByVal UserName As String) As Boolean
'Dim MyIdentity As System.Security.Principal.WindowsIdentity = New WindowsPrincipal(New WindowsIdentity(UserName)) ' System.Security.Principal.WindowsIdentity.GetCurrent()
'Dim userPrincipal = New WindowsPrincipal(New WindowsIdentity(Username))
Dim MyPrincipal As System.Security.Principal.WindowsPrincipal = New WindowsPrincipal(New WindowsIdentity(UserName)) 'New System.Security.Principal.WindowsPrincipal(userPrincipal)
Return MyPrincipal.IsInRole("XXX_YYY")
End Function
Also Tried to do something like this but getting the error i screenshotted.
Public Function IsInGroup(ByVal UserName As String) As Boolean
Dim Result As Boolean
Dim de As New DirectoryEntry("LDAP://AD")
Dim MemberSearcher As New DirectorySearcher
With MemberSearcher
.SearchRoot = de
.Filter = "(&(ObjectClass=Group)(CN=VAL_ITS))"
.PropertiesToLoad.Add("Member")
End With
Dim mySearchResults As SearchResult = MemberSearcher.FindOne()
For Each User In mySearchResults.Properties("Member")
If User = UserName Then
Result = True
Else
Result = False
End If
Next
Return Result
End Function
'Project > Add Reference > System.DirectoryServices.AccountManagement & System.DirectoryServices
Validate using the System.DirectoryServices.AccountManagement namespace
Imports System.DirectoryServices.AccountManagement
Public function validate(username as string, password as string, domain as string)
Dim valid As Boolean = False
Using context As New PrincipalContext(ContextType.Domain, domain)
valid = context.ValidateCredentials(username, password)
End Using
return valid
End Function
Public function checkgroup(domain as string, username as string, groupname as string)
Dim isMember as boolean = false
Dim ctx As New PrincipalContext(ContextType.Domain, domain)
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, username)
Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupname)
If user IsNot Nothing Then
If user.IsMemberOf(group) Then
isMember = True
End If
End If
return isMember
End Function

Can't get attributes from AD using vb.net

I use below code to get first name, last name, email, and department from AD using VB.Net 1.1
Public Shared Function GetAttribute(ByVal username As String, ByVal pwd As String) As UserInfo
Dim objUserInfo As New UserInfo
Dim ObjFirstName As String = ""
Dim ObjLastName As String = String.Empty
Dim ObjEmail As String = ""
Dim objDepartment As String = ""
Dim Success As Boolean = False
Dim LDAPAddress As String = ConfigurationSettings.AppSettings.Get("LDAPAddress")
Dim Entry As New System.DirectoryServices.DirectoryEntry(LDAPAddress, username, pwd)
Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
Dim Filter As String = "(samAccountName=" & username & ")"
Dim findUser As DirectorySearcher = New DirectorySearcher(Entry, Filter)
Dim results As SearchResultCollection = findUser.FindAll
Try
Dim Resultsx As System.DirectoryServices.SearchResult = Searcher.FindOne
Success = Not (Resultsx Is Nothing)
findUser.PropertiesToLoad.Add("name")
Dim name As String = DirectCast(Resultsx.Properties(name)(0), String)
Dim de As System.DirectoryServices.DirectoryEntry = Resultsx.GetDirectoryEntry()
Dim gg = de.Properties.PropertyNames()
For Each Onn As String In gg
Dim str As String = String.Format("{0}", Onn)
Next
Try
ObjFirstName = de.Properties("GivenName").Value.ToString()
ObjEmail = de.Properties("mail").Value.ToString()
ObjLastName = de.Properties("sn").Value.ToString()
objDepartment = de.Properties("department").Value.ToString()
Catch ex As Exception
ObjFirstName = de.Properties("DisplayName").Value.ToString()
End Try
But I can't get those attributes. in
Dim str As String = String.Format("{0}", Onn)
there are only 15 attributes, and there are no firstname, lastname, email, and department. What am I doing wrong?
Your code, though old-fashioned, looks fine on first sight. If you insist to continue with your code, I'll have a look later.
In the meantime, this code should fit your situation:
Dim user As DirectoryEntry = New DirectoryEntry("UserDN")
Dim src As DirectorySearcher = New DirectorySearcher(user, "(&(objectClass=user)(objectCategory=Person))")
src.PropertiesToLoad.Add("sn")
src.PropertiesToLoad.Add("givenName")
src.PropertiesToLoad.Add("mail")
src.PropertiesToLoad.Add("department")
Dim res As SearchResult = src.FindOne
Console.WriteLine(res.Properties("sn")(0))
Console.WriteLine(res.Properties("givenName")(0))
Console.WriteLine(res.Properties("mail")(0))
Console.WriteLine(res.Properties("department")(0))
Console.ReadLine()

How to use the log in details from one form in another?

I'm creating a windows form application and I have made the sign up process so the users data is saved to a record. I have also got it so that when you go to sign in it search my records for a e-mail that is typed in and checks if the password matches. Now on the next form of the 'Signed In Page' I want to display the other information from that record on the page probably in a listbox. Any ideas?
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSignIn.Click
Dim RecordNumber As Integer
Dim Found As Boolean
Dim foundpword As Boolean
Dim UserEmail As String
Dim userPword As String
Dim OneAccount As fmSignUp.SignUpInfo
Dim stripeditem As String
Dim strippword As String
Dim CurrentUser As String
UserEmail = tbEmailSignIn.Text
userPword = tbPasswordSignIn.Text
Found = False
FileOpen(1, filename, OpenMode.Random, , , Len(OneAccount))
Do While (Not EOF(1)) And (Found = False)
RecordNumber = RecordNumber + 1
FileGet(1, OneAccount, RecordNumber)
stripeditem = OneAccount.ContactEmail.Replace(" ", "")
strippword = OneAccount.Password.Replace(" ", "")
If stripeditem = UserEmail Then
Found = True
End If
If strippword = userPword Then
foundpword = True
End If
Loop
FileClose(1)
This is where I declare the record.
Dim OneAccount As fmSignUp.SignUpInfo
filename = "AccountDetails.dat"
FileOpen(1, filename, OpenMode.Random, , , Len(OneAccount))
NumberOfRecords = LOF(1) / Len(OneAccount)
FileClose(1)
Simplest is to crate a public method on current form
that returns a variable or a list of string that contains all information
you require from one form,
then in other form u can do:
Dim frm As Form1 = new Form1()
Dim tmp as string;
tmp = frm.ThatMethod()
See following as well:
Using Variables Across Forms - VB

How do I get the users that belong to a group in Active Directory?

I have a dropdownlist that I am trying to fill with users that belong to a certain group in Active Directory.
The group name is OverRiders and 8 people are members of this group. More members could be added.
I have the following dropdown but I run the code, the dropdown is blank.
What am I doing wrong?
Please see code:
Private Sub FillDropdown()
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://CN=OverRiders,OU=Departments,DC=domain,DC=com")
Dim osearcher As DirectorySearcher = New DirectorySearcher(oroot)
Dim oresult As SearchResultCollection
Dim result As SearchResult
Dim list As New List(Of String)
osearcher.Filter = "(&(objectCategory=group)(cn={0}))"
' search filter; only display emp with firstname / lastname pair
osearcher.PropertiesToLoad.Add("name") ' member
oresult = osearcher.FindAll()
For Each result In oresult
If Not result.GetDirectoryEntry.Properties("name").Value Is Nothing Then
list.Add(result.GetDirectoryEntry.Properties("name").Value.ToString())
Call list.Sort()
End If
Next
emplist.DataSource = list
emplist.DataBind()
End Sub
I have been able to confirm that the group does exist and the group name is valid.
Thanks a lot in advance
Changed:
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://CN=OverRiders,OU=Departments,DC=domain,DC=com")
to
Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://DC=domain,DC=com")
and this:
osearcher.Filter = "(&(objectCategory=group)(cn={0}))"
to this:
osearcher.Filter = "(&(objectCategory=user)(memberOf=CN=overRiders,OU=Departments,DC=domain,DC=com)‌​)"
Everything else remain unchanged.
Hope it helps someone else.
I know this is an old question, but this is what worked for me in a similar situation:
Dim UsersInGroup As New Collection()
Dim de As New DirectoryEntry("LDAP://[Domain]")
Dim MemberSearcher As New DirectorySearcher
With MemberSearcher
.SearchRoot = de
.Filter = "(&(ObjectClass=Group)(CN=" & Group & "))"
.PropertiesToLoad.Add("Member")
End With
Dim mySearchResults As SearchResult = MemberSearcher.FindOne()
For Each User In mySearchResults.Properties("Member")
UsersInGroup.Add(User)
Next

AD not returning the groups which authenticated user belong to

I'm able to authenticate given user - Domain, UserName and Password with LDAP but not able to retrive his groups which he associated with :(
Here the code i'm using
Public Function ValidateActiveDirectoryLogin(ByVal domainName As String, ByVal userName As String, ByVal userPassword As String) As Boolean
Dim isValidated As Boolean = False
Try
Dim ldapPath As String = "LDAP://" & domainName
Dim dirEntry As New DirectoryEntry(ldapPath, userName, userPassword, AuthenticationTypes.Secure)
Dim dirSearcher As New DirectorySearcher(dirEntry)
dirSearcher.Filter = "(SAMAccountName=" & userName & ")"
dirSearcher.PropertiesToLoad.Add("memberOf")
Dim result As SearchResult = dirSearcher.FindOne()
If Not result Is Nothing Then
For Each x As DictionaryEntry In result.Properties
x.Key.ToString()
'DirectCast(x, System.Collections.DictionaryEntry).Key()
Next
Dim groupCount As Integer = result.Properties("memberOf").Count
Dim isInGroup As Boolean = False
For index As Integer = 0 To groupCount - 1
Dim groupDN As String = result.Properties("memberOf").Item(index).ToString
Dim equalsIndex As Integer = groupDN.IndexOf("=")
Dim commaIndex As Integer = groupDN.IndexOf(",")
Dim group As String = groupDN.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).ToLower
If group.Equals(groupName.ToLower) Then
isInGroup = True
Exit For
End If
Next index
isValidated = isInGroup
End If
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
Return isValidated
End Function
Please help...
Venky
Here is the way I will use, sorry it's code I translate from C# to VB.Net
` Connection to Active Directory
Dim deBase As DirectoryEntry = New DirectoryEntry("LDAP://192.168.183.100:389/dc=dom,dc=fr", "jpb", "pwd")
` Directory Search for the group your are interested in
Dim dsLookForGrp As DirectorySearcher = New DirectorySearcher(deBase)
dsLookForGrp.Filter = String.Format("(cn={0})", "yourgroup")
dsLookForGrp.SearchScope = SearchScope.Subtree
dsLookForGrp.PropertiesToLoad.Add("distinguishedName")
Dim srcGrp As SearchResult = dsLookForGrp.FindOne
If (Not (srcGrp) Is Nothing) Then
Dim dsLookForUsers As DirectorySearcher = New DirectorySearcher(deBase)
dsLookForUsers.Filter = String.Format("(&(objectCategory=person)(memberOf={0}))", srcGrp.Properties("distinguishedName")(0))
dsLookForUsers.SearchScope = SearchScope.Subtree
dsLookForUsers.PropertiesToLoad.Add("objectSid")
dsLookForUsers.PropertiesToLoad.Add("userPrincipalName ")
dsLookForUsers.PropertiesToLoad.Add("sAMAccountName")
Dim srcLstUsers As SearchResultCollection = dsLookForUsers.FindAll
For Each sruser As SearchResult In srcLstUsers
Console.WriteLine("{0}", sruser.Path)
` Here Test if you username is insode
Console.WriteLine(""& vbTab&"{0} : {1} ", "sAMAccountName", sruser.Properties("sAMAccountName")(0))
Next
End If
Be careful the primary group is given by the primaryGroupID and it's not a DN but an ID which is the lasr part of the group SID.
Last thing, But you can also do it using Managing Directory Security Principals in the .NET Framework 3.5. Here is a sample in C#
/* Retreiving a principal context
*/
Console.WriteLine("Retreiving a principal context");
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD");
/* Look for all the groups a user belongs to
*/
UserPrincipal aUser = UserPrincipal.FindByIdentity(domainContext, "user1");
PrincipalSearchResult<Principal> a = aUser.GetAuthorizationGroups();
foreach (GroupPrincipal gTmp in a)
{
Console.WriteLine(gTmp.Name);
}