Determine whether a domain user is a member of a group based on Recursive deep priority.
Reference System. directoryservices
And import the namespace
Using
System. directoryservices;
Function: determines whether the domain user (login name) is a member of a domain security group. The domain user may belong to multiple groups and may belong to multiple groups. Therefore, recursive calls are required.
Private
Directoryentry entry
=
New
Directoryentry (
"
LDAP: // domain
"
,
@"
Domain \ Username
"
,
"
Password
"
);
Private
Bool
Userisgroupmember (
String
Userlogin,
String
Rolename)
{
Directorysearcher mysearcher
=
New
Directorysearcher (entry );
Mysearcher. Filter
=
String
. Format (
"
(& (Objectclass = user) (samaccountname = {0 }))
"
, Userlogin );
Mysearcher. propertiestoload. Add (
"
Memberof
"
);
Searchresult mysr
=
Mysearcher. findone ();
If
(Mysr. properties. Count
>
1
)
//
Two attributes are returned, one is the built-in adspath, and the other is the propertiestoload loaded
{
String
[] Memberof
=
New
String
[Mysr. properties [
"
Memberof
"
]. Count];
Int
I
=
0
;
Foreach
(Object mycoll
In
Mysr. properties [
"
Memberof
"
])
{
Memberof [I]
=
Mycoll. tostring (). substring (
3
, Mycoll. tostring (). indexof (
"
,
"
)
-
3
);
If
(Memberof [I]
=
Rolename)
Return
True
;
I
++
;
} // In fact, this layer of loop is a breadth-first algorithm, because considering that a person directly belongs to a security group is more likely, this is more efficient. if the following loop is placed in the IF esle above, the depth is given priority.
Foreach
(
String
Groupname
In
Memberof)
If
(Memberisgroupmember (groupname, rolename ))
Return
True
;
}
Return
False
;
}
Private
Bool
Memberisgroupmember (
String
Groupname,
String
Rolename)
{
Directorysearcher mysearcher
=
New
Directorysearcher (entry );
Mysearcher. Filter
=
String
. Format (
"
(& (Objectclass = Group) (CN = {0 }))
"
, Groupname );
Mysearcher. propertiestoload. Add (
"
Memberof
"
);
Searchresult mysr
=
Mysearcher. findone ();
String
Memberof;
If
(Mysr. properties. Count
>
1
)
//
Two attributes are returned, one is the built-in adspath, and the other is the propertiestoload loaded
{
Foreach
(Object mycoll
In
Mysr. properties [
"
Memberof
"
])
{
Memberof
=
Mycoll. tostring (). substring (
3
, Mycoll. tostring (). indexof (
"
,
"
)
-
3
);
If
(Memberof
=
Rolename)
Return
True
;
Else
If
(Memberisgroupmember (memberof, rolename ))
Return
True
;
}
}
Return
False
;
}