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

前端 未结 14 1179
花落未央
花落未央 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:58

    This seems much simpler:

    public bool IsInRole(string groupname)
    {
        var myIdentity = WindowsIdentity.GetCurrent();
        if (myIdentity == null) return false;
    
        var myPrincipal = new WindowsPrincipal(myIdentity);
        var result = myPrincipal.IsInRole(groupname);
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-30 20:02

    With 3.5 and System.DirectoryServices.AccountManagement this is a bit cleaner:

    public List<string> GetGroupNames(string userName)
    {
      var pc = new PrincipalContext(ContextType.Domain);
      var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc);
      var result = new List<string>();
      src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
      return result;
    }
    
    0 讨论(0)
提交回复
热议问题