See if user is part of Active Directory group in C# + Asp.net

前端 未结 14 1242
花落未央
花落未央 2020-11-30 19:06

I need a way to see if a user is part of an active directory group from my .Net 3.5 asp.net c# application.

I am using the standard ldap authentication example off o

14条回答
  •  攒了一身酷
    2020-11-30 19:43

    Nick Craver's solution doesn't work for me in .NET 4.0. I get an error about an unloaded AppDomain. Instead of using that, I used this (we only have one domain). This will check groups of groups as well as direct group membership.

    using System.DirectoryServices.AccountManagement;
    using System.Linq;
    
    ...
    
    using (var ctx = new PrincipalContext(ContextType.Domain, yourDomain)) {
        using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, yourGroup)) {
            bool isInRole = grp != null && 
                grp
                .GetMembers(true)
                .Any(m => m.SamAccountName == me.Identity.Name.Replace(yourDomain + "\\", ""));
        }
    }
    

提交回复
热议问题