Results 1 to 8 of 8

Thread: Check if user is a member of an Active Directory Group

  1. #1

    Thread Starter
    Addicted Member silentthread's Avatar
    Join Date
    Jun 2006
    Location
    Miami, Florida
    Posts
    143

    Thumbs up Check if user is a member of an Active Directory Group

    With the help of some threads in this forum, I was able to put this together.

    This is a function that you pass it the username and the AD group. If it finds a match, it returns true, else false. That way you can control what users can see on the webpage based on their AD rights.

    To use the code below, you must be able to get the username. I believe you need to turn of anonymous access on the virtual directory, via mycomputer, right-click, manage, default website etc.

    Add this to your webconfig file....

    Code:
    <identity impersonate="true" />
    And call something like....

    dim NTLogin as string = Replace(Environment.UserName, "Mydomain\", "")

    To remove the domain name. If you still have problems getting the username, there are many threads in this forum that assist with that.

    Okay, Here is the function for checking if a user is a member of an AD group.
    Please post questions, concerns, comments, suggestions, etc.


    VB Code:
    1. Public Function Check_If_Member_Of_AD_Group(ByVal username As String, _
    2.     ByVal grouptoCheck As String, _
    3.     ByVal domain As String, _
    4.     ByVal ADlogin As String, _
    5.     ByVal ADpassword As String) _
    6.     As Boolean
    7.  
    8.         'This is a function that receives a username to see if it's a
    9.         'member of a specific group in AD.
    10.  
    11.  
    12.         Try
    13.             'First let's put the whole thing in a nice big try catch, and
    14.             'catch any errors.
    15.  
    16.             Dim EntryString As String
    17.             EntryString = "LDAP://" & domain
    18.             'Above, we setup the LDAP basic entry string.
    19.  
    20.             Dim myDE As DirectoryEntry
    21.             'Above, I dimension my DirectoryEntry object
    22.  
    23.  
    24.             grouptoCheck = grouptoCheck.ToLower()
    25.             'The groups returned may have different combinations of
    26.             'lowercase and uppercase, so let's go ahead
    27.             'and make grouptoCheck lowercase.
    28.  
    29.  
    30.             If (ADlogin <> "" AndAlso ADpassword <> "") Then
    31.                 'If they provided a password, then add it
    32.                 'as an argument to the function
    33.                 'I recently learned about AndAlso, and it's pretty
    34.                 'cool. Basically it does not worry about checking
    35.                 'the next condition if the first one is not true.
    36.                 myDE = New DirectoryEntry(EntryString, ADlogin, ADpassword)
    37.                 'Above, we create a new instance of the Directory Entry
    38.                 'Includes login and password
    39.             Else
    40.                 'Else, use the account credentials of the machine
    41.                 'making the request. You might not be able to get
    42.                 'away with this if your production server does not have
    43.                 'rights to query Active Directory.
    44.                 'Then again, there are workarounds for anything.
    45.                 myDE = New DirectoryEntry(EntryString)
    46.                 'Above, we create a new instance of the Directory Entry
    47.                 'Does not include login and password
    48.             End If
    49.  
    50.             Dim myDirectorySearcher As New DirectorySearcher(myDE)
    51.             'Above we create new instance of a DirectorySearcher
    52.             'We also specify the Directory Entry as an argument.
    53.  
    54.             myDirectorySearcher.Filter = "sAMAccountName=" & username
    55.             'Above we specify to filter our results where
    56.             'sAMAccountName is equal to our username passed in.
    57.             myDirectorySearcher.PropertiesToLoad.Add("MemberOf")
    58.             'We only care about the MemberOf Properties, and we
    59.             'specify that above.
    60.  
    61.             Dim myresult As SearchResult = myDirectorySearcher.FindOne()
    62.             'SearchResult is a node in Active Directory that is returned
    63.             'during a search through System.DirectoryServices.DirectorySearcher
    64.             'Above, we dim a myresult object, and assign a node returned
    65.             'from myDirectorySearcher.FindOne()
    66.             'I've never heard of similar login Id's in Active Directory,
    67.             'so I don't think we need to call FindAll(), so Instead
    68.             'we call FindOne()
    69.  
    70.  
    71.             Dim NumberOfGroups As Integer
    72.             NumberOfGroups = myresult.Properties("memberOf").Count() - 1
    73.             'Above we get the number of groups the user is a memberOf,
    74.             'and store it in a variable. It is zero indexed, so we
    75.             'remove 1 so we can loop through it.
    76.  
    77.             Dim tempString As String
    78.             'A temp string that we will use to get only what we
    79.             'need from the MemberOf string property
    80.  
    81.             While (NumberOfGroups >= 0)
    82.                 tempString = myresult.Properties("MemberOf").Item(NumberOfGroups)
    83.                 tempString = tempString.Substring(0, tempString.IndexOf(",", 0))
    84.                 'Above we set tempString to the first index of "," starting
    85.                 'from the zeroth element of itself.
    86.                 tempString = tempString.Replace("CN=", "")
    87.                 'Above, we remove the "CN=" from the beginning of the string
    88.                 tempString = tempString.ToLower() 'Lets make all letters lowercase
    89.                 tempString = tempString.Trim()
    90.                 'Finnally, we trim any blank characters from the edges
    91.  
    92.                 If (grouptoCheck = tempString) Then
    93.                     Return True
    94.                 End If
    95.                 'If we have a match, the return is true
    96.                 'username is a member of grouptoCheck
    97.  
    98.                 NumberOfGroups = NumberOfGroups - 1
    99.             End While
    100.  
    101.  
    102.             'If the code reaches here, there was no match.
    103.             'Return false
    104.             Return False
    105.  
    106.  
    107.         Catch ex As Exception
    108.  
    109.             HttpContext.Current.Response.Write("Error: <br><br>" & ex.ToString)
    110.  
    111.         End Try
    112.  
    113.  
    114.     End Function
    Last edited by silentthread; Jul 10th, 2006 at 05:18 PM.
    Watch media as you download it! Excellent tool!
    FREE CUBA!
    MyBlog
    If you feel my post has helped, please rate it.

  2. #2

    Thread Starter
    Addicted Member silentthread's Avatar
    Join Date
    Jun 2006
    Location
    Miami, Florida
    Posts
    143

    Re: Check if user is a member of an Active Directory Group

    I want to mention that a buddy of mine mentioned to me that this function does not search for nested group memberships. If you want to tackle that one, then go for it.

    If I ever need something like that, then I will put something together.
    Last edited by silentthread; Jul 21st, 2006 at 08:08 PM.
    Watch media as you download it! Excellent tool!
    FREE CUBA!
    MyBlog
    If you feel my post has helped, please rate it.

  3. #3

    Thread Starter
    Addicted Member silentthread's Avatar
    Join Date
    Jun 2006
    Location
    Miami, Florida
    Posts
    143

    Re: Check if user is a member of an Active Directory Group

    2 things to note.......

    a- If you are placing this on a production asp.net server, you will need to provide the LDAP account in the following fashion.....
    mydomainblablah\bubbasLDAP_account
    The prefixing of the domain is not important on your localhost though.

    b- If you need to search nested group memberships, this can really beat up your asp.net server. We recently created an app that copies all the information from active directory into a SQL database. This copying happens automatically everynight.
    This method of querying nested group memberships from a SQL database has drastically increased our web applications performance.
    Watch media as you download it! Excellent tool!
    FREE CUBA!
    MyBlog
    If you feel my post has helped, please rate it.

  4. #4
    PowerPoster
    Join Date
    Mar 2005
    Posts
    2,580

    Re: Check if user is a member of an Active Directory Group

    hi silentthread and sorry me..
    But this code is in VB.net?
    I need a similar code to check if member is in group but in vb classic, have one?
    Tks.

  5. #5

    Thread Starter
    Addicted Member silentthread's Avatar
    Join Date
    Jun 2006
    Location
    Miami, Florida
    Posts
    143

    Re: Check if user is a member of an Active Directory Group

    It should not be too hard. Sorry, I don't have that handy. You might want to look for sites like this one.....
    http://labs.developerfusion.co.uk/co...to-csharp.aspx
    in which they convert to different languages. I doubt though that someone will have a vb.net to vb code converter.
    Watch media as you download it! Excellent tool!
    FREE CUBA!
    MyBlog
    If you feel my post has helped, please rate it.

  6. #6
    New Member
    Join Date
    Aug 2008
    Posts
    1

    Re: Check if user is a member of an Active Directory Group

    Quote Originally Posted by silentthread
    2 things to note.......

    a- If you are placing this on a production asp.net server, you will need to provide the LDAP account in the following fashion.....
    mydomainblablah\bubbasLDAP_account
    The prefixing of the domain is not important on your localhost though.

    b- If you need to search nested group memberships, this can really beat up your asp.net server. We recently created an app that copies all the information from active directory into a SQL database. This copying happens automatically everynight.
    This method of querying nested group memberships from a SQL database has drastically increased our web applications performance.
    Can you reference some resources on how you copied AD to SQL? I'd be interested in pursuing this.

  7. #7
    New Member
    Join Date
    Sep 2010
    Posts
    1

    Re: Check if user is a member of an Active Directory Group

    Quote Originally Posted by jrhyne2584 View Post
    Can you reference some resources on how you copied AD to SQL?chat room software I'd be interested in pursuing this.
    there is a tool coming along with sql management studio (import/export data), you can use it to transfer database from any regular format to sql
    Last edited by zurab0274; Sep 8th, 2010 at 11:11 AM.

  8. #8
    New Member
    Join Date
    Dec 2011
    Posts
    1

    Thumbs up Re: Check if user is a member of an Active Directory Group

    Thank you silentthread.

    Its helps me a lot. I needed the function in C#, so I translate it. Think I could post this here, beside it is a VB forum.

    Code:
            public Boolean Check_If_Member_Of_AD_Group(String username, String grouptoCheck, String domain, String ADlogin, String ADpassword)
            {
                //This is a function that receives a username to see if it's a
                //member of a specific group in AD.
                try
                {
                    //'First let's put the whole thing in a nice big try catch, and
                    //'catch any errors.
                    String EntryString;
                    EntryString = "LDAP://" + domain;
                    //'Above, we setup the LDAP basic entry string.
                    DirectoryEntry myDE;
                    //'Above, I dimension my DirectoryEntry object
                    grouptoCheck = grouptoCheck.ToLower();
                    //'The groups returned may have different combinations of
                    //'lowercase and uppercase, so let's go ahead
                    //'and make grouptoCheck lowercase.
                    if (ADlogin != "" && ADpassword != "")
                    {
                        //'If they provided a password, then add it
                        //'as an argument to the function
                        //'I recently learned about AndAlso, and it's pretty
                        //'cool. Basically it does not worry about checking
                        //'the next condition if the first one is not true.
                        myDE = new DirectoryEntry(EntryString, ADlogin, ADpassword);
                        //'Above, we create a new instance of the Directory Entry
                        //'Includes login and password
                    }
                    else
                    {
                        //'Else, use the account credentials of the machine
                        //'making the request. You might not be able to get
                        //'away with this if your production server does not have
                        //'rights to query Active Directory.
                        //'Then again, there are workarounds for anything.
                        myDE = new DirectoryEntry(EntryString);
                        //'Above, we create a new instance of the Directory Entry
                        //'Does not include login and password
                    }
                    DirectorySearcher myDirectorySearcher = new DirectorySearcher(myDE);
                    //'Above we create new instance of a DirectorySearcher
                    //'We also specify the Directory Entry as an argument.
                    myDirectorySearcher.Filter = "sAMAccountName=" + username;
                    //'Above we specify to filter our results where
                    //'sAMAccountName is equal to our username passed in.
                    myDirectorySearcher.PropertiesToLoad.Add("MemberOf");
                    myDirectorySearcher.PropertiesToLoad.Add("Name");
                    //'We only care about the MemberOf Properties, and we
                    //'specify that above.
                    SearchResult myresult = myDirectorySearcher.FindOne();
                    //'SearchResult is a node in Active Directory that is returned
                    //'during a search through System.DirectoryServices.DirectorySearcher
                    //'Above, we dim a myresult object, and assign a node returned
                    //'from myDirectorySearcher.FindOne()
                    //'I've never heard of similar login Id's in Active Directory,
                    //'so I don't think we need to call FindAll(), so Instead
                    //'we call FindOne()
                    if(myresult.Properties["Name"].Count > 0)
                    {
                        loggedName = myresult.Properties["Name"][0].ToString();
                    }
    
                    Int32 NumberOfGroups;
                    NumberOfGroups = myresult.Properties["memberOf"].Count - 1;
                    //'Above we get the number of groups the user is a memberOf,
                    //'and store it in a variable. It is zero indexed, so we
                    //'remove 1 so we can loop through it.
                    String tempString;
                    //'A temp string that we will use to get only what we
                    //'need from the MemberOf string property
                    while (NumberOfGroups >= 0)
                    {
                        tempString = myresult.Properties["MemberOf"][NumberOfGroups].ToString();
                        tempString = tempString.Substring(0, tempString.IndexOf(",", 0));
                        //'Above we set tempString to the first index of "," starting
                        //'from the zeroth element of itself.
                        tempString = tempString.Replace("CN=", "");
                        //'Above, we remove the "CN=" from the beginning of the string
                        tempString = tempString.ToLower(); //'Lets make all letters lowercase
                        tempString = tempString.Trim();
                        //'Finnally, we trim any blank characters from the edges
                        if (grouptoCheck == tempString)
                        {
                            return true;
                        }
                        //'If we have a match, the return is true
                        //'username is a member of grouptoCheck
                        NumberOfGroups = NumberOfGroups - 1;
                    }
                    //'If the code reaches here, there was no match.
                    //'Return false
                    return false;
                }
    
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("Error: <br><br>" + ex.ToString());
                }
                return false;
            }
    Tks again.
    Hernandes Moreira

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width