/build/static/layout/Breadcrumb_cap_w.png

C#.net Check if user is in Active Directory Group

Here is a simple c#.net function to see if a user is in a AD group.

Be sure to add the Directory Services as a refrence to your project and use:

using System.DirectoryServices.AccountManagement;

private static bool IsInGroup(string ingroup)
        {
            string username = Environment.UserName;

            PrincipalContext domainctx = new PrincipalContext(ContextType.Domain,
                                                        "example",
                                                        "DC=example,DC=com");

            UserPrincipal userPrincipal =
                              UserPrincipal.FindByIdentity(domainctx, IdentityType.SamAccountName, username);

            bool isMember = userPrincipal.IsMemberOf(domainctx, IdentityType.Name, ingroup);

            return isMember;
        }


Then in your script call IsInGroup("group name, i.e. administrators") and it will return a true or false bool for you to test on. 


Comments

This post is locked

Don't be a Stranger!

Sign up today to participate, stay informed, earn points and establish a reputation for yourself!

Sign up! or login

Share

 
This website uses cookies. By continuing to use this site and/or clicking the "Accept" button you are providing consent Quest Software and its affiliates do NOT sell the Personal Data you provide to us either when you register on our websites or when you do business with us. For more information about our Privacy Policy and our data protection efforts, please visit GDPR-HQ