Is UserName A Member Of An AD Security Group?

I am using the code below to check if the user logged onto the PC is a member of a specific AD Security Group.  Now I need to perform the same task with a username the user types into a web page and I capture in a string variable (Becaise the user on the web page may not be the user logged into the PC).  I'm not sure how to edit the GetGroups Function to allow the username to be passed from a string.

public string IsInGroup(string strGroup)
    {
        bool _Test = false;
        string strTest = "False";
            // collect the user domain and identity
        string[] arr =
            System.Web.HttpContext.Current.Request.
            LogonUserIdentity.Name.Split('\\');

         ArrayList al = new ArrayList();
        al = GetGroups();

        // check to see if the user belongs
        // to a specific group and create
        // a list of all of the user's groups
        foreach (string s in al)
        {
            // check to see if the user
            // belongs to a specific group
            if (s == strGroup)
            {
                _Test = true;
                //return strTest = "True";
            }
           
        }
        if (_Test == false)
        {
            return strTest = "False";
        }
        else {
            return strTest = "True";
        }
       
      }
    public ArrayList GetGroups()
    {
        ArrayList groups = new ArrayList();
        foreach (System.Security.Principal.IdentityReference group in
        System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
        {
            groups.Add(group.Translate(typeof
            (System.Security.Principal.NTAccount)).ToString());
        }
        return groups;
    }
robtrollerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MlandaTCommented:
try these:


Dim cbx as New PrincipalContext(ContextType.Domain,domainName)
Dim user as UserPrincipal = UserPrincipal.findByIdentity(cbx,userName)
Dim groupResults as PrincipalSearchResult(Of Principal) = user.GetGroups()
For Each p as Principal in groupResults
    blGroups.Items.Add(p.Name)
Next

Open in new window

ArrayList results = new ArrayList();

PrincipalContext context = new
PrincipalContext(ContextType.Domain, "DC", "DC=DOMAIN,DC=COM", "domain\\user", "password"); //the account with privileges to get the 

UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "usertogetgroups");

var groups = p.GetAuthorizationGroups();

foreach (var group in groups)
{
	results.Add(group.Name);
}
return results;

Open in new window

0
robtrollerAuthor Commented:
I'm not having any luck converting this to C#.  In a nutshell, I wan to query AD for user Security Groups based on a string tht contains the username instead of using the System.Security.Principal.IdentityReference.  Seems like it shouldn't be an unusual thing to do as we can pass a username to the DirectoryEntry object to validate username & password.  I'm really stuck on this.  Any C# assistance would be greately appreciated.
0
MlandaTCommented:
the second example I gave you is actually c#
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

robtrollerAuthor Commented:
OK, trying again.  I am missint a system reference do you know which one?
0
robtrollerAuthor Commented:
Current references are :

using System;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
0
MlandaTCommented:
I have knocked up a sample for you.

In your applicaiton, remember that you need to add a reference to System.DirectoryServices.AccountManagement (in System.DirectoryServices.AccountManagement.dll)
DemoActiveDirectory.zip
0
robtrollerAuthor Commented:
This is the code I used to verify the user's group membership.  The search is recursive so it will find the user if they are not a member of the search group but are a member of a sub group.

public static bool searchMembers(string uname, string group)
    {
        // new ldap object
        DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=tufts-nemc,dc=org");
        // new searcher object
        DirectorySearcher srch = new DirectorySearcher(rootEntry);
        srch.SearchScope = SearchScope.Subtree;           // make the search recursive
        srch.PropertiesToLoad.Add("samaccountname");      // get the name
        srch.PropertiesToLoad.Add("objectclass");         // get the type
       
        // create the filter that will find all members of the given group
        srch.Filter = "(&(memberof=CN=" + group + ",OU=<OU>,OU=<OU>,DC=<DC>))";

        // for each result (each member of the group), do something
        foreach (SearchResult s in srch.FindAll())
        {
            // if it's a person
            if (s.Properties["objectclass"][1].ToString() == "person")
            {
                if (s.Properties["samaccountname"][0].ToString().ToLower() == uname)
                {
                    return true;
                }
                else
                {
                    continue;
                }
            }
            // else, if it's a group
            else if (s.Properties["objectclass"][1].ToString() == "group")
            {
                string newGroup = s.Properties["samaccountname"][0].ToString();
                ADAuth a = new ADAuth();
                // use searchnewGroup to search the contents of the group for the username
                if (a.searchnewGroup(uname, newGroup))
                {
                    return true;
                }
            }
        }
        return false;
    }
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
robtrollerAuthor Commented:
This is how I resolved the issue
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.