コード例 #1
0
ファイル: HomeController.cs プロジェクト: AlanDotson/onrr
        private List <GroupPrincipal> GetGroups(string userName)
        {
            var result = new List <GroupPrincipal>();
            var ctx    = GetContext();
            var user   = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName);

            if (user != null)
            {
                PrincipalSearchResult <Principal> groups = user.GetGroups();

                var iterGroup = groups.GetEnumerator();
                using (iterGroup)
                {
                    while (iterGroup.MoveNext())
                    {
                        try
                        {
                            Principal p = iterGroup.Current;
                            result.Add((GroupPrincipal)p);
                        }
                        catch (PrincipalOperationException)
                        {
                            continue;
                        }
                    }
                }
            }

            return(result);
        }
コード例 #2
0
        /// <summary>
        /// Получить список ролей пользователя AD
        /// </summary>
        /// <param name="adLogin">логин AD</param>
        /// <returns>Список ролей из AD</returns>
        private string[] GetUsersADRoles(string adLogin)
        {
            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) {
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx, adLogin);

                if (user != null)
                {
                    // Только такая реализация. ToArray() и подобное не подходят, из за бага, который MS исправлять
                    // не планируют в виду "разумного" способа обхода проблемы (игнорирования исключения???).
                    // А ведь на багу ещё наткнуться надо (плавающий баг) и понять от чего у пользователя проблемы. Козлы...
                    // FYI https://stackoverflow.com/questions/39525430/system-directoryservices-accountmanagement-nomatchingprincipalexception-an-erro
                    List <string> list = new List <string>();
                    PrincipalSearchResult <Principal> groups    = user.GetAuthorizationGroups();
                    IEnumerator <Principal>           itemGroup = groups.GetEnumerator();
                    using (itemGroup) {
                        while (itemGroup.MoveNext())
                        {
                            try {
                                Principal p = itemGroup.Current;
                                list.Add(p.Name);
                            }
                            catch (NoMatchingPrincipalException) {
                                // Это фишка решения...
                                continue;
                            }
                        }

                        return(list.ToArray());
                    }
                }
            }

            return(new string[0]);
        }
コード例 #3
0
ファイル: ActiveDirectory.cs プロジェクト: ompel/WindAPI
        /// <summary>
        /// This method receives a UserMembershipResult object containing a username to check
        /// and get all of the AD groups the user is a member of
        /// </summary>
        /// <param name="membershipResult">A UserMembershipResult object containing a username
        /// to check.</param>
        /// <returns>A UserMembershipResult object containing the username to check, a result message,
        /// a status code for the AD query and the list of groups the user is a member of.</returns>
        public static UserMembershipResult GetAllGroupsByUser(UserMembershipResult membershipResult)
        {
            // Create output group names list.
            membershipResult.groups  = new List <string>();
            membershipResult.message = string.Empty;

            // Set up domain context.
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain, Constants.adQueryUser, Constants.adQueryPassword);

            // Find the user in AD.
            UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, membershipResult.user);

            if (user != null)
            {
                PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups();

                // Defining iterator object.
                var iterator = groups.GetEnumerator();
                using (iterator)
                {
                    while (iterator.MoveNext())
                    {
                        try
                        {
                            Principal p = iterator.Current;
                            if (p is GroupPrincipal)
                            {
                                membershipResult.groups.Add(p.SamAccountName);
                            }
                        }
                        catch (NoMatchingPrincipalException pex)
                        {
                            if (membershipResult.code != 1)
                            {
                                membershipResult.message = pex.Message;
                                membershipResult.code    = 1;
                            }
                            continue;
                        }
                    }
                }

                if (membershipResult.message == string.Empty)
                {
                    membershipResult.message = "Group list generated successfully";
                    membershipResult.code    = 0;
                }

                return(membershipResult);
            }
            membershipResult.message = "Input user not found in Active Directory";
            membershipResult.code    = 2;
            return(membershipResult);
        }
コード例 #4
0
        public IList <string> GetGroupsForADUser(string loginName, string domain)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(domain));

            try
            {
                var groupList = new List <string>();

                // PrincipalContext encapsulates the server or domain against which all operations are performed.
                using (var pc = new PrincipalContext(ContextType.Domain, domain))
                {
                    // Create a reference to the user account we are querying against.
                    UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, loginName);

                    if (up == null)
                    {
                        return(new List <string>());
                    }

                    //Get the user's security groups.  This is necessary to return nested groups, but will NOT return distribution groups.
                    PrincipalSearchResult <Principal> groups = up.GetAuthorizationGroups();

                    // add each group to our groupList.  We have to use the Enumerator pattern to iterate over the elements in the
                    // groups collection and ignore any NoMatchingPrincipalException because of a _bug in ActiveDirectory's GetAuthorizationGroups()
                    // method.
                    // See: https://social.msdn.microsoft.com/Forums/vstudio/en-US/9dd81553-3539-4281-addd-3eb75e6e4d5d/getauthorizationgroups-fails-with-nomatchingprincipalexception?forum=csharpgeneral
                    var groupsEnumerator = groups.GetEnumerator();
                    while (groupsEnumerator.MoveNext())
                    {
                        try
                        {
                            var group = groupsEnumerator.Current;

                            if (group != null && !string.IsNullOrWhiteSpace(group.SamAccountName))
                            {
                                groupList.Add(group.SamAccountName);
                            }
                        }
                        catch (NoMatchingPrincipalException)
                        {
                        }
                    }
                }

                return(groupList);
            }
            catch (PrincipalServerDownException ex)
            {
                Exception innerMostEx = ex.GetBaseException();
                throw new AuthenticationException("Could not authenticate against the Active Directory server.  The AD server could not be contacted.", innerMostEx);
            }
        }
コード例 #5
0
        protected void getGrupos(UserPrincipal usuario)
        {
            PrincipalSearchResult <Principal> coleccionGrupos = usuario.GetGroups();

            var enumerador = coleccionGrupos.GetEnumerator();
            {
                lstGrupos.Items.Clear();
                while (enumerador.MoveNext())
                {
                    lstGrupos.Items.Add(new ListItem(enumerador.Current.ToString()));
                }
            }
        }
コード例 #6
0
 protected void getUsuarios(PrincipalContext contexto)
 {
     if (usuario.Name.Trim() == "Administrator")
     {
         UserPrincipal     usuario  = new UserPrincipal(contexto);
         PrincipalSearcher buscador = new PrincipalSearcher(usuario);
         PrincipalSearchResult <Principal> coleccionUsuarios = buscador.FindAll();
         Apodo2.Text = "Usted es el Administrator";
         var enumerador = coleccionUsuarios.GetEnumerator();
         {
             downListUsuarios.Items.Clear();
             while (enumerador.MoveNext())
             {
                 downListUsuarios.Items.Add(new ListItem(enumerador.Current.ToString()));
             }
         }
     }
     else
     {
         downListUsuarios.Items.Clear();
         downListUsuarios.Items.Add(this.usuario.DisplayName.ToString());
     }
 }
コード例 #7
0
        //add application specific Claims to user's identity
        private static ClaimsPrincipal AddCustomClaimsToPrincipal(String userName)
        {
            PrincipalContext princiContxt = null;
            UserPrincipal    thePrincipal = null;

            //get the Domain context for the Directory Services
            princiContxt = new PrincipalContext(ContextType.Domain);

            //get the user-principal object from the Domain context using the specified username
            thePrincipal = UserPrincipal.FindByIdentity(princiContxt, userName);

            var customClaims = new List <System.Security.Claims.Claim> {
                new System.Security.Claims.Claim(ClaimTypes.Email, userName),
                new System.Security.Claims.Claim(ClaimTypes.Name, userName)
            };

            if (userName == "*****@*****.**")
            {
                var findItem = customClaims.Find(c => c.Value == "SuperAdmin");
                if (findItem == null)
                {
                    customClaims.Add(new System.Security.Claims.Claim("Group", "SuperAdmin"));
                }
            }
            if (thePrincipal != null)
            {
                if (thePrincipal.Surname != null)
                {
                    customClaims.Add(new System.Security.Claims.Claim(ClaimTypes.WindowsAccountName, thePrincipal.SamAccountName));
                    customClaims.Add(new System.Security.Claims.Claim(ClaimTypes.Surname, thePrincipal.Surname));
                }
                // get all groups the user is a member of
                ////
                //// Todo for a weird error on crm dev server. uncomment the below line if you can solve it!
                ////
                //customClaims.AddRange(thePrincipal.GetAuthorizationGroups().Select(group =>
                //    new System.Security.Claims.Claim("AD_Group", group.Name)));
                PrincipalSearchResult <Principal> adGroup = thePrincipal.GetAuthorizationGroups();
                var iterGroup = adGroup.GetEnumerator();
                using (iterGroup)
                {
                    while (iterGroup.MoveNext())
                    {
                        try
                        {
                            var p = iterGroup.Current;
                            if (string.IsNullOrEmpty(p.Name))
                            {
                                continue;
                            }
                            customClaims.Add(new System.Security.Claims.Claim("AD_Group", p.Name));
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                //here you can add any claim type-value pairs, maybe some user settings read from DB.
                var db          = new ApplicationDbContext();
                var userManager = new ApplicationUserStore(db);
                var user        = userManager.Users.FirstOrDefault(u => u.Email == thePrincipal.UserPrincipalName);

                if (user != null)
                {
                    customClaims.Add(new System.Security.Claims.Claim("UserId", user.Id.ToString()));
                    var claims     = user.ApplicationClaims;
                    var groups     = user.ApplicationGroups;
                    var rowFilters = user.ApplicationPrincipalRowFilters.Where(x => x.PrincipalType == "U");

                    var groupManager     = new ApplicationGroupStore(db);
                    var claimManager     = new ApplicationClaimStore(db);
                    var rowFilterManager = new RowFilterStore(db);

                    customClaims.AddRange(groups.Select(group => groupManager.FindById(group.ApplicationGroupId)).Select(g =>
                                                                                                                         new System.Security.Claims.Claim("Group", g.Name)));
                    customClaims.AddRange(claims.Select(claim => claimManager.FindById(claim.ApplicationClaimId)).Select(c =>
                                                                                                                         new System.Security.Claims.Claim(c.Key, c.Value)));
                    customClaims.AddRange(rowFilters.Select(r => rowFilterManager.FindById(r.Id)).Select(c =>
                                                                                                         new System.Security.Claims.Claim(c.ApplicationRowFilterType.Name, c.RowFilterValue.ToString())));

                    var appgroupManager = new ApplicationGroupManager();
                    var groupList       = groups.Select(group => groupManager.FindById(group.ApplicationGroupId));
                    foreach (var item in groupList)
                    {
                        var groupRowFilters = item.ApplicationPrincipalRowFilters.Where(x => x.PrincipalType == "G");
                        customClaims.AddRange(groupRowFilters.Select(r => rowFilterManager.FindById(r.Id)).Select(c =>
                                                                                                                  new System.Security.Claims.Claim(c.ApplicationRowFilterType.Name, c.RowFilterValue.ToString())));

                        foreach (var appclaim in appgroupManager.GetGroupClaims(item.Id))
                        {
                            var claim    = new System.Security.Claims.Claim(appclaim.Key, appclaim.Value);
                            var findItem = customClaims.Find(c => c.Value == claim.Value && c.Type == claim.Type);
                            if (findItem == null)
                            {
                                customClaims.Add(claim);
                            }
                        }
                    }
                }
            }

            //https://msdn.microsoft.com/en-us/library/system.security.claims.authenticationtypes(v=vs.110).aspx
            var theCustomClaimsIdentity = new ClaimsIdentity(customClaims, authenticationType: "Negotiate");//Negotiate | Signing | Sealing

            return(new ClaimsPrincipal(theCustomClaimsIdentity));
        }
        private static IList <Claim> GetOutputClaims(string userName, PrincipalContext context)
        {
            List <Claim> claims = new List <Claim>();

            UserPrincipal user = UserPrincipal.FindByIdentity(context, GetUserNoDomain(userName));

            string upn = GetUserPrincipalName(user);

            claims.Add(new Claim(ClaimTypes.Upn, upn));
            claims.Add(new Claim(ClaimTypes.Sid, user.Sid.ToString()));

            LogEntry entry;

            bool foundGroups = false;

            if (context.ContextType != ContextType.Machine)
            {
                entry          = new LogEntry();
                entry.Severity = TraceEventType.Information;
                entry.Priority = -1;

                if (Logger.ShouldLog(entry))
                {
                    entry.Message = "Getting authorization groups from WindowsIdentity...";
                    Logger.Write(entry);
                }

                try
                {
                    using (WindowsIdentity identity = new WindowsIdentity(upn))
                    {
                        foreach (IdentityReference group in identity.Groups)
                        {
                            claims.Add(new Claim(ClaimTypes.GroupSid, group.Value));
                        }
                    }

                    foundGroups = true;
                }
                catch (UnauthorizedAccessException ex)
                {
                    entry          = new LogEntry();
                    entry.Severity = TraceEventType.Error;
                    entry.Priority = -1;

                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = ex.ToString();
                        Logger.Write(entry);
                    }
                }
                catch (SecurityException ex)
                {
                    entry          = new LogEntry();
                    entry.Severity = TraceEventType.Error;
                    entry.Priority = -1;

                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = ex.ToString();
                        Logger.Write(entry);
                    }
                }
            }

            if (!foundGroups)
            {
                entry          = new LogEntry();
                entry.Severity = TraceEventType.Information;
                entry.Priority = -1;

                if (Logger.ShouldLog(entry))
                {
                    entry.Message = "Getting authorization groups from UserPrincipal...";
                    Logger.Write(entry);
                }

                try
                {
                    using (PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups())
                    {
                        var enumerator = groups.GetEnumerator();

                        while (enumerator.MoveNext())
                        {
                            try
                            {
                                using (Principal p = enumerator.Current)
                                {
                                    if (p.Sid != null)
                                    {
                                        claims.Add(new Claim(ClaimTypes.GroupSid, p.Sid.ToString()));
                                    }
                                }
                            }
                            catch (NoMatchingPrincipalException)
                            {
                            }
                            catch (PrincipalOperationException)
                            {
                            }
                        }
                    }
                }
                catch (PrincipalOperationException ex)
                {
                    entry          = new LogEntry();
                    entry.Severity = TraceEventType.Error;
                    entry.Priority = -1;

                    if (Logger.ShouldLog(entry))
                    {
                        entry.Message = ex.ToString();
                        Logger.Write(entry);
                    }
                }
            }

            entry          = new LogEntry();
            entry.Severity = TraceEventType.Verbose;
            entry.Priority = -1;

            if (Logger.ShouldLog(entry))
            {
                StringBuilder sb = new StringBuilder();

                foreach (Claim claim in claims)
                {
                    if (claim.ClaimType == ClaimTypes.GroupSid)
                    {
                        sb.AppendLine(string.Format("Found Group SID: {0}", claim.Value));
                    }
                }

                entry.Message = sb.ToString();

                Logger.Write(entry);
            }

            return(claims);
        }
コード例 #9
0
        public override string[] GetRolesForUser(string username)
        {
            this.Log("username:"******"SELECT Roles.Rolename FROM Roles INNER JOIN UsersRoles ON Roles.Id = UsersRoles.IdRole INNER JOIN Users ON UsersRoles.IdUser = Users.Id WHERE Users.Username = @Username ORDER BY Roles.Rolename", connection))
                        {
                            cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = username;
                            connection.Open();
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        roles.Add(reader.GetString(0));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    this.Log(e.Message, MethodBase.GetCurrentMethod().Name);
                    throw new ProviderException(e.Message);
                }

                this.Log("Roles:" + string.Join(",", roles.ToArray()), MethodBase.GetCurrentMethod().Name);
                return(roles.ToArray());
            }

            string domain = null;
            string name   = null;
            LinkedList <string> source = new LinkedList <string>();

            try
            {
                ADUtil.splitDomainAndName(username, out domain, out name);
                if ((domain == null) || domain.Equals(""))
                {
                    domain = this.dnsroot2NETBIOSName[this.currentDomainName];
                }
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, null, domain, this.userNameAD, this.passwordAD))
                {
                    using (UserPrincipal principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, name))
                    {
                        if (principal == null)
                        {
                            throw new ProviderException("Unable to find user '" + username + "'.");
                        }
                        using (PrincipalSearchResult <Principal> result = principal.GetAuthorizationGroups())
                        {
                            using (IEnumerator <Principal> enumerator = result.GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    try
                                    {
                                        using (Principal principal2 = enumerator.Current)
                                        {
                                            if ((principal2 != null) && (principal2 is GroupPrincipal))
                                            {
                                                using (GroupPrincipal principal3 = (GroupPrincipal)principal2)
                                                {
                                                    if ((principal3.DistinguishedName != null) && principal3.IsSecurityGroup.Value)
                                                    {
                                                        source.AddLast(this.ncname2NETBIOSName[ADUtil.getDCcomponent(principal3.DistinguishedName)] + @"\" + principal3.SamAccountName);
                                                    }
                                                }
                                            }
                                        }
                                        continue;
                                    }
                                    catch (Exception)
                                    {
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                this.Log(exception.Message, MethodBase.GetCurrentMethod().Name);
                throw new ProviderException("Getting roles for user '" + username + "' failed.", exception);
            }

            if (this.useRolesDBforAD)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(this.connectionString))
                    {
                        using (SqlCommand cmd = new SqlCommand("SELECT Roles.Rolename FROM Roles INNER JOIN UsersRolesAD ON Roles.Id = UsersRolesAD.IdRole WHERE UsersRolesAD.Username = @Username ORDER BY Roles.Rolename", connection))
                        {
                            cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = username;
                            connection.Open();
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        source.AddLast(reader.GetString(0));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    this.Log(e.Message, MethodBase.GetCurrentMethod().Name);
                    throw new ProviderException("Getting roles for user '" + username + "' failed.", e);
                }
            }

            this.Log("Roles:" + string.Join(",", source.ToArray <string>()), MethodBase.GetCurrentMethod().Name);
            return(source.ToArray <string>());
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: joe-scalise/GetADGroups
        static void Main(string[] args)
        {
            // Test for secrets file or just use
            // string domain = "domain.local";
            string domain = null;

            try
            {
                domain = System.IO.File.ReadAllText(@"C:\temp\secrets\domain.txt");
            }
            catch
            {
                Console.WriteLine("\nThere's a problem with the domain file.");
            }

            if (!(string.IsNullOrEmpty(domain)))
            {
                Console.Write("\nEnter user name: ");
                string userName = Console.ReadLine();
                Console.WriteLine("\nSearching domain " + domain);

                List <string> userGroupList = new List <string>();

                using (var context = new PrincipalContext(ContextType.Domain, domain))
                {
                    using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
                    {
                        if (userPrincipal != null)
                        {
                            PrincipalSearchResult <Principal> list = userPrincipal.GetAuthorizationGroups();

                            int count = 1;

                            var iterGroup = list.GetEnumerator();

                            using (iterGroup)
                            {
                                Console.WriteLine();
                                while (iterGroup.MoveNext())
                                {
                                    try
                                    {
                                        Principal p = iterGroup.Current;
                                        if (!(string.IsNullOrEmpty(p.SamAccountName)))
                                        {
                                            Console.WriteLine(count + ": " + p.SamAccountName.ToLower().Trim());
                                            userGroupList.Add(p.SamAccountName.ToLower().Trim());
                                            count++;
                                        }
                                        else
                                        {
                                            Console.WriteLine("\n* NULL encountered; group " + p.Name + " *\n");
                                        }
                                    }
                                    catch (NoMatchingPrincipalException pex)
                                    {
                                        Console.WriteLine("\n* NoMatchingPrincipalException encountered *\n");
                                        continue;
                                    }
                                }
                            }

                            // Just test that this operation does not fail
                            userGroupList.Sort();

                            Console.WriteLine("\nEnd of list of groups.");
                        }
                        else
                        {
                            Console.WriteLine("\nUser was not found.");
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("\nDomain string is missing.");
            }

            Console.WriteLine("\nEnd of program.  Press enter to exit.");
            Console.ReadLine();
        }