如何检查用户是否属于AD组?

Sea*_*_05 51 .net c# active-directory winforms c#-4.0

起初我认为下面的代码有效,因为如果我将该组作为"IT"它正常运行,因为我的用户名在活动目录中的IT组中.我学到的是,无论我是否在IT组中拥有我的用户名,它总是返回,如果我将其更改为我所在的任何其他组,则返回始终返回false.任何帮助,将不胜感激.

    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);
    }
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 102

由于您使用的是.NET 3.5及更高版本,因此您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间.在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松查找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.....
   } 
}
Run Code Online (Sandbox Code Playgroud)

新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!


Gol*_*hop 12

与@marc_s示例略有偏差,在以下static void Main()方法中实现Program:

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

DomainCtx并且User都是声明的静态属性Program

然后在其他形式我只是做这样的事情:

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

}
Run Code Online (Sandbox Code Playgroud)