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

后端 未结 3 1397
灰色年华
灰色年华 2020-11-30 23:53

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 learn

相关标签:
3条回答
  • 2020-12-01 00:19

    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

    0 讨论(0)
  • 2020-12-01 00:30

    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
    
    }
    
    0 讨论(0)
  • 2020-12-01 00:41

    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:

    • Managing Directory Security Principals in the .NET Framework 3.5
    • MSDN docs on System.DirectoryServices.AccountManagement

    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!

    0 讨论(0)
提交回复
热议问题