Friday, January 5, 2018

Check if a user is in an AD group.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;

namespace test_adgroup
{
   class Program
    {
       static void Main(string[] args)
        {
           string username = "cykill";
           //string username = WindowsIdentity.GetCurrent().Name;

           PrincipalContext pc = new PrincipalContext(ContextType.Domain,"mydomainname");
           UserPrincipal up = UserPrincipal.FindByIdentity(pc, username);

           if(up.IsMemberOf(pc,IdentityType.SamAccountName,"mygroup"))
            {
               Console.WriteLine("In Group");
            }
           else
            {
               Console.WriteLine("Not In Group");
            }

        }
    }
}

Caveat:  This does not work for the "Domain Users" group.  It always return false.  I don't know why.
Update:  Seems it doesn't work for large AD groups.

No comments:

Post a Comment

Thank you for your comment.