简体   繁体   中英

c# comparing current windows user to AD group

I am trying to grab the current windows user and see if that user is part of a certain group in Active Directory. The username information finds "Harper\\TSmith" which seems fine but when I get to the

UserPrincipal uPrincipal = Psearch.FindOne() as UserPrincipal

Line UPrincipal is null. Can not figure out why. I also have at the bottom a validator class that as a bool method to see if they are part of that particular group.

PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
            UserPrincipal findUser = new UserPrincipal(principalCtx);
            //findUser.Name = Environment.UserName;
            findUser.Name = WindowsIdentity.GetCurrent().Name;
            PrincipalSearcher pSearch = new PrincipalSearcher();
            pSearch.QueryFilter = findUser;
            UserPrincipal uPrincipal = pSearch.FindOne() as UserPrincipal;

            Validator validate = new Validator();
            //validate.IsUserInGroup("VisualOne", uPrincipal);

            if (validate.IsUserInGroup("MyGroup", uPrincipal))
            {
                var MemberShipForm = new Membership();
                MemberShipForm.Show();
            }



public bool IsUserInGroup(string groupName, UserPrincipal user)
    {
        PrincipalContext context = new PrincipalContext(ContextType.Domain, "Harper");
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "MyGroup");

        if (user.IsMemberOf(group))
        {
            return true;
        }
        return false;
    }
PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
UserPrincipal uPrincipal = UserPrincipal.Current;

 if (validate.IsUserInGroup("MyGroup", uPrincipal))
            {
                var MemberShipForm = new Membership();
                MemberShipForm.Show();
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM