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

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

    How to check user is in AD member and specific AD group member

    //This Reference and DLL must be attach in your project         
    //using System.DirectoryServices.AccountManagement;        
    
    
             public bool IsAuthenticated(string username, string pwd)
            {
    
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "xxx.com"))   // Your Domain Name
                {
                    if (pc.ValidateCredentials(username, password))  //User and Password is OK for Active Directory 
                    {
                        UserPrincipal user = UserPrincipal.FindByIdentity(pc, username);  //Get User Active Directory Information Details
                        if (user != null)
                        {
    
                            var groups = user.GetAuthorizationGroups();   // Get User Authorized Active Directory Groups
                            foreach (GroupPrincipal group in groups)
                            {
                                if (group.Name.Equals("SpecificActiveDirectoryGroupName"))  //Check if user specific group members
                                { 
                                    return true;
                                }
    
                            }
                        }
                    }
                }
                return false;
            }
    

提交回复
热议问题