How to check if a user belongs to an AD group?

C#.NetWinformsC# 4.0Active Directory

C# Problem Overview


At first I thought the code below works because if I have the group as "IT" it functions correctly because my username is in the IT group in active directory. What I learned is it always returns true whether I have my username in the IT group or not and if i change it to any other group I am in it returns always returns false. Any help would be appreciated.

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // tab control security for admin tab
        bool admin = checkGroup("IT");

        if ((admin == true) && (tabControl1.SelectedTab == tpHistory))
        {
            tabControl1.SelectedTab = tpHistory;
        }
        else if ((admin == false) && (tabControl1.SelectedTab == tpHistory))
        {
            tabControl1.SelectedTab = tpRequests;
            MessageBox.Show("Unable to load tab. You have insufficient privileges.",
                "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    }

    // check active directory to see if user is in Marketing department group
    private static bool checkGroup(string group)
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole(group);
    }

C# Solutions


Solution 1 - C#

Since 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:

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, "DOMAINNAME");

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

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

if(user != null)
{
   // check if user is member of that group
   if (user.IsMemberOf(group))
   {
     // do something.....
   } 
}

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

Solution 2 - C#

Slight deviation from @marc_s example, implemented in the static void Main() method in Program:

DomainCtx = new PrincipalContext( ContextType.Domain , Environment.UserDomainName );
if ( DomainCtx != null ) {
	User = UserPrincipal.FindByIdentity( DomainCtx , Environment.UserName );
}

DomainCtx and User are both static properties declared under Program

Then in other forms i simply do something like this:

if ( Program.User.IsMemberOf(GroupPrincipal.FindByIdentity(Program.DomainCtx, "IT-All") )) {
	//Enable certain Form Buttons and objects for IT Users
	
}

Solution 3 - C#

You cannot do it by this way. You should query the active directory. You can use a wrapper for AD. Check out http://www.codeproject.com/Articles/10301/Wrapper-API-for-using-Microsoft-Active-Directory-S

Solution 4 - C#

Check if current user in a group

public bool AuthenticateGroup(string groupfind)
        {
            var p = new Process();
            StringBuilder stringbd = new StringBuilder();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = @"/c gpresult /V";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.UseShellExecute = false;
            p.OutputDataReceived += (a, b) => stringbd.AppendLine(b.Data);
            p.ErrorDataReceived += (a, b) => stringbd.AppendLine(b.Data);
            p.Start();
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            p.WaitForExit();
            var textfind = stringbd.ToString();
            int findpoint = textfind.IndexOf("The user is a part of");
            string findgroup = "";
            if (findpoint > 0)
            {
                findgroup = textfind.Substring(findpoint, textfind.Length - findpoint);
            }

            return findgroup.Split('\n').ToList().Any(r=>r.Trim().ToLower()==groupfind.Trim().ToLower());
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSealer_05View Question on Stackoverflow
Solution 1 - C#marc_sView Answer on Stackoverflow
Solution 2 - C#GoldBishopView Answer on Stackoverflow
Solution 3 - C#Ibrahim ULUDAGView Answer on Stackoverflow
Solution 4 - C#Hung Tran DIView Answer on Stackoverflow