Exemplo n.º 1
0
        internal DirectoryEntry GetUser(User user, ActiveDirectory ad, ActiveDirectoryGroup group)
        {
            var ou         = GetOU(group);
            var adInfo     = ad; //user.ActiveDirectory;
            var domainPath = GetDomainPath(adInfo.LDAPRoot, adInfo.DCInfo, ou, "");

            using (
                var de = new DirectoryEntry(domainPath, adInfo.AdminName, adInfo.AdminPwd, AuthenticationTypes.Secure))
            {
                var deSearch = new DirectorySearcher(de);
                deSearch.Filter      = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + user.UserName + "))";
                deSearch.SearchScope = SearchScope.Subtree;

                try
                {
                    SearchResult result = deSearch.FindOne();
                    var          sde    = new DirectoryEntry(result.Path);

                    return(sde);
                }
                catch
                {
                    return(null);
                }
            }
        }
Exemplo n.º 2
0
        internal ADGroup[] GetAuthorizationGroups(string partitionDN, string principalDN)
        {
            this.Init();
            GetADPrincipalAuthorizationGroupRequest getADPrincipalAuthorizationGroupRequest = new GetADPrincipalAuthorizationGroupRequest();

            getADPrincipalAuthorizationGroupRequest.PrincipalDN = principalDN;
            getADPrincipalAuthorizationGroupRequest.PartitionDN = partitionDN;
            GetADPrincipalAuthorizationGroupResponse aDPrincipalAuthorizationGroup = this._acctMgmt.GetADPrincipalAuthorizationGroup(this._sessionHandle, getADPrincipalAuthorizationGroupRequest);
            List <ADGroup> aDGroups = new List <ADGroup>();

            if (aDPrincipalAuthorizationGroup.MemberOf == null)
            {
                return(new ADGroup[0]);
            }
            else
            {
                ActiveDirectoryGroup[] memberOf = aDPrincipalAuthorizationGroup.MemberOf;
                for (int i = 0; i < (int)memberOf.Length; i++)
                {
                    ActiveDirectoryGroup activeDirectoryGroup = memberOf[i];
                    ADGroup aDGroup = new ADGroup();
                    this.PopulateADGroupFromWebServiceData(activeDirectoryGroup, aDGroup);
                    aDGroups.Add(aDGroup);
                }
                return(aDGroups.ToArray());
            }
        }
Exemplo n.º 3
0
        ///// <summary>
        ///// 获取AD组
        ///// </summary>
        ///// <param name="ad"></param>
        ///// <param name="group"></param>
        ///// <returns></returns>
        //internal DirectoryEntry GetADGroup(ActiveDirectory ad, ActiveDirectoryGroup group)
        //{
        //    var groupName = group.Name;
        //    try
        //    {
        //        var domainPath = GetDomainPath(ad.LDAPRoot, ad.DCInfo, group.OrganizationUnits, "");
        //        var de = new DirectoryEntry(domainPath, ad.AdminName, ad.AdminPwd, AuthenticationTypes.Secure);
        //        return GetADGroup(de, ad, group.Name);
        //    }
        //    catch
        //    {
        //    }
        //    return null;
        //}
        /// <summary>
        /// 修改用户全名、邮件地址
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="ad"></param>
        /// <param name="group">用户隶属于组</param>
        public void ChangeUserInfo(User user, ActiveDirectory ad, ActiveDirectoryGroup group)
        {
            var ou = GetOU(group);
            //throw new NotImplementedException();
            var adInfo     = ad; //user.ActiveDirectory;
            var domainPath = GetDomainPath(adInfo.LDAPRoot, adInfo.DCInfo, ou, "CN=" + user.UserName);

            using (var us = new DirectoryEntry(domainPath, adInfo.AdminName, adInfo.AdminPwd, AuthenticationTypes.Secure))
            {
                if (user.Profile != null)
                {
                    var comparer    = StringComparer.OrdinalIgnoreCase;
                    var oldEmail    = us.Properties["mail"].Value == null ? null : us.Properties["mail"].Value.ToString();
                    var oldFullname = us.Properties["displayName"].Value == null ? null : us.Properties["displayName"].Value.ToString();
                    //us.Properties["name"].Value = user.Profile.FullName ?? user.UserName;
                    if (!comparer.Equals(oldEmail, user.Profile.Email))
                    {
                        us.Properties["mail"].Value = user.Profile.Email ?? user.Email;
                    }
                    if (!comparer.Equals(oldFullname, user.Profile.FullName))
                    {
                        us.Properties["displayName"].Value = user.Profile.FullName ?? user.UserName;
                    }
                    us.CommitChanges();
                }
            }
        }
Exemplo n.º 4
0
 public void UpdateActiveDirectoryGroup(ActiveDirectoryGroup group)
 {
     if (group == null)
     {
         throw new ArgumentNullException("group");
     }
     _groupRepo.Update(group);
 }
Exemplo n.º 5
0
 public void RemoveActiveDirectory(ActiveDirectoryGroup group)
 {
     if (group == null)
     {
         throw new ArgumentNullException("group");
     }
     _groupRepo.Delete(group);
 }
Exemplo n.º 6
0
 public void AddActiveDirectoryGroup(ActiveDirectoryGroup group)
 {
     if (group == null)
     {
         throw new ArgumentNullException("group");
     }
     _groupRepo.Insert(group);
 }
Exemplo n.º 7
0
        /// <summary>
        /// 在AD域中新建用户
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="ad"></param>
        /// <param name="group">用户隶属于的组格式:OU=Web组,OU=开发部</param>
        public void CreateADUser(User user, ActiveDirectory ad, ActiveDirectoryGroup group)
        {
            throw new NotImplementedException();
            //var ou = GetOU(group);
            ////var hasUser = HasUser(user,ou);
            ////if(hasUser) throw new Exception("域中已存在该用户"+user.UserName);
            ////user.ActiveDirectoryId = ad.Id;
            //user.Domain = ad.Domain;
            //var adInfo = ad; //user.ActiveDirectory;
            //var domainPath = GetDomainPath(adInfo.LDAPRoot, adInfo.DCInfo, ou, "");
            //using (
            //    var de = new DirectoryEntry(domainPath, adInfo.AdminName, adInfo.AdminPwd, AuthenticationTypes.Secure))
            //{
            //    using (var us = de.Children.Add("CN=" + user.UserName, "user"))
            //    {
            //        var name = user.UserName;
            //        if (user.Profile != null)
            //        {
            //            name = user.Profile.FullName ?? user.UserName;
            //        }
            //        us.Properties["sAMAccountName"].Add(user.UserName); //account
            //        us.Properties["userPrincipalName"].Value = user.UserName; //user logon name,[email protected]
            //        us.Properties["givenName"].Value = name; //名
            //        //us.Properties["sn"].Value = "张";
            //        us.Properties["name"].Value = name; //full name

            //        us.Properties["displayName"].Value = name;

            //        us.Properties["mail"].Value = user.Email;

            //        us.CommitChanges();
            //        //反射调用设置密码的方法(注意端口号的问题  端口号会引起方法调用异常)
            //        var pass = Utility.DecryptText(user.Password, user.PrivateKey);
            //        us.Invoke("SetPassword", new object[] {pass});
            //        //默认设置新增账户启用
            //        us.Properties["userAccountControl"].Value = 0x10200;
            //        us.CommitChanges();
            //    }

            //    var groupDe = GetADGroup(de, ad, group.Name);
            //    if (groupDe == null)
            //    {
            //        groupDe = CreateADGroup(de, group.Name);
            //    }
            //    if (groupDe != null)
            //    {
            //        using (groupDe)
            //        {
            //            var userDN = "CN=" + user.UserName + "," + group.OrganizationUnits + "," + adInfo.DCInfo;
            //            groupDe.Properties["member"].Add(userDN);
            //            groupDe.CommitChanges();
            //        }
            //    }

            //}
        }
        public JsonResult MembershipsOfUser(string userName)
        {
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);

            try
            {
                UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName);

                // "userName"e sahip kullanıcı bulunursa
                if (user != null)
                {
                    // Kullanıcının kayıtlı olduğu gruplar bulunuyor
                    PrincipalSearchResult <Principal> principalList = user.GetGroups();

                    List <ActiveDirectoryGroup> groups = new List <ActiveDirectoryGroup>();

                    foreach (Principal found in principalList)
                    {
                        ActiveDirectoryGroup currentGroup = new ActiveDirectoryGroup();
                        currentGroup.groupName = found.Name;

                        // Grubun ismi verilerek, "security" veya "mail" grubu olduğu kontrol ediliyor.
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, currentGroup.groupName);

                        if (group.IsSecurityGroup == true)
                        {
                            currentGroup.isSecurityGroup = true;
                        }
                        else
                        {
                            currentGroup.isSecurityGroup = false;
                        }

                        groups.Add(currentGroup);
                    }

                    return(Json(groups, JsonRequestBehavior.AllowGet));
                }
                // "userName"e sahip kullanıcı bulunamazsa, "null" data gönderiliyor.
                else
                {
                    return(Json(true));
                }
            }
            catch (MultipleMatchesException)
            {
                // Aynı ad-soyad'la kayıtlı birden çok kullanıcı varsa, "kayıt bulunamadı" mesajı döndürülüyor.
                // Kullanıcıya ulaşmak için "username" veya "mail" ile aramak yapmak gerekiyor.
                return(Json(true));
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 变更用户密码
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="ad"></param>
        /// <param name="ou">用户隶属于组</param>
        public void ChangeUserPassword(User user, ActiveDirectory ad, ActiveDirectoryGroup group)
        {
            var ou         = GetOU(group);
            var adInfo     = ad; //user.ActiveDirectory;
            var domainPath = GetDomainPath(adInfo.LDAPRoot, adInfo.DCInfo, ou, "CN=" + user.UserName);

            using (var de = new DirectoryEntry(domainPath, adInfo.AdminName, adInfo.AdminPwd, AuthenticationTypes.Secure))
            {
                var pass = Utility.DecryptText(user.Password, user.PrivateKey);
                de.Invoke("SetPassword", new object[] { pass });
                de.CommitChanges();
                de.RefreshCache();
            }
        }
        private DialogResult EditEntry(ActiveDirectoryGroup group)
        {
            DialogResult result = DialogResult.None;

            using (var form = new ActiveDirectoryGroupManagementForm(_masterItemsList, _selectedItemsList, group))
            {
                result = form.ShowDialog();
                if (result == DialogResult.OK)
                {
                    _unsavedChanges = true;
                }
            }

            return(result);
        }
Exemplo n.º 11
0
        private IEnumerable <AccessManagement> ReadAccessManagements(IResourceGroup resourceGroup)
        {
            var accessManagement  = new AccessManagement(resourceGroup);
            var accessManagements = new List <AccessManagement> {
                accessManagement
            };
            var azureAccessManagement = _azure.AccessManagement;

            // Microsoft.Azure.Management.Graph.RBAC.Fluent.Models.GraphErrorException
            // Operation returned an invalid status code 'Forbidden'
            foreach (var activeDirectoryGroup in azureAccessManagement.ActiveDirectoryGroups.List())
            {
                var group = new ActiveDirectoryGroup(activeDirectoryGroup.Name);
                accessManagement.ActiveDirectoryGroups.Add(group);
            }

            foreach (var activeDirectoryApplication in azureAccessManagement.ActiveDirectoryApplications.List())
            {
                var application = new ActiveDirectoryApplication(activeDirectoryApplication.Name);
                accessManagement.ActiveDirectoryApplications.Add(application);
            }

            foreach (var activeDirectoryUser in azureAccessManagement.ActiveDirectoryUsers.List())
            {
                var user = new ActiveDirectoryUser(activeDirectoryUser.Name);
                accessManagement.ActiveDirectoryUsers.Add(user);
            }

            ////foreach (var roleAssignment in azureAccessManagement.RoleAssignments.ListByScope())
            ////{
            ////    var assignment = new RoleAssignment(roleAssignment.Name);
            ////    accessManagement.RoleAssignments.Add(assignment);
            ////}

            ////foreach (var roleDefinition in azureAccessManagement.RoleDefinitions.ListByScope())
            ////{
            ////    var definition = new ActiveDirectoryUser(roleDefinition.Name);
            ////    accessManagement.RoleDefinitions.Add(definition);
            ////}

            foreach (var servicePrincipal in azureAccessManagement.ServicePrincipals.List())
            {
                var principal = new ServicePrincipal(servicePrincipal.Name);
                accessManagement.ServicePrincipals.Add(principal);
            }

            return(accessManagements);
        }
Exemplo n.º 12
0
        public ActiveDirectoryGroupManagementForm
        (
            Collection <GroupPrincipal> masterItemsList,
            SortableBindingList <ActiveDirectoryGroup> selectedItemsList,
            ActiveDirectoryGroup group
        )
        {
            InitializeComponent();
            UserInterfaceStyler.Configure(this, FormStyle.FixedDialog);

            _masterItemsList   = masterItemsList;
            _selectedItemsList = selectedItemsList;
            _group             = group;

            groupName_ComboBox.DisplayMember = "Name";
        }
        private void add_ToolStripButton_Click(object sender, EventArgs e)
        {
            ActiveDirectoryGroup group = new ActiveDirectoryGroup();

            if (EditEntry(group) == DialogResult.OK)
            {
                _context.AddToActiveDirectoryGroups(group);
                _selectedItemsList.Add(group);

                int index = activeDirectory_DataGridView.Rows.Count - 1;

                activeDirectory_DataGridView.Rows[index].Selected = true;

                //In case if you want to scroll down as well.
                activeDirectory_DataGridView.FirstDisplayedScrollingRowIndex = index;
            }
        }
Exemplo n.º 14
0
        private void PopulateADGroupFromWebServiceData(ActiveDirectoryGroup inputWSGroup, ADGroup groupToPopulate)
        {
            ActiveDirectoryGroupScope groupScope = inputWSGroup.GroupScope;

            switch (groupScope)
            {
            case ActiveDirectoryGroupScope.DomainLocal:
            {
                groupToPopulate.GroupScope = new ADGroupScope?(ADGroupScope.DomainLocal);
                break;
            }

            case ActiveDirectoryGroupScope.Global:
            {
                groupToPopulate.GroupScope = new ADGroupScope?(ADGroupScope.Global);
                break;
            }

            case ActiveDirectoryGroupScope.Universal:
            {
                groupToPopulate.GroupScope = new ADGroupScope?(ADGroupScope.Universal);
                break;
            }
            }
            ActiveDirectoryGroupType groupType = inputWSGroup.GroupType;

            switch (groupType)
            {
            case ActiveDirectoryGroupType.Distribution:
            {
                groupToPopulate.GroupCategory = new ADGroupCategory?(ADGroupCategory.Distribution);
                break;
            }

            case ActiveDirectoryGroupType.Security:
            {
                groupToPopulate.GroupCategory = new ADGroupCategory?(ADGroupCategory.Security);
                break;
            }
            }
            this.PopulateADPrincipalFromWebServiceData(inputWSGroup, groupToPopulate);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Helper method populates a collection of groups.
        /// </summary>
        /// <param name="results">System.DirectoryServices.SearchResultCollection</param>
        private void CreateGroupCollection(SearchResultCollection results)
        {
            string groupName      = null;
            string samAccountName = null;

            foreach (SearchResult groupObject in results)
            {
                ActiveDirectoryGroup group    = new ActiveDirectoryGroup();
                PropertyCollection   propcoll = groupObject.GetDirectoryEntry().Properties;
                foreach (string key in groupObject.GetDirectoryEntry().Properties.PropertyNames)
                {
                    //loop through all the values associated with our key
                    foreach (object values in propcoll[key])
                    {
                        // get the group name of this entry
                        if (string.Compare(key, "cn", true, _culture) == 0)
                        {
                            groupName = values.ToString();
                        }
                        // get the samAccountName name of this entry
                        if (string.Compare(key, "samAccountName", true, _culture) == 0)
                        {
                            samAccountName = values.ToString();
                        }
                        // get the member name of this entry
                        if (string.Compare(key, "member", true, _culture) == 0)
                        {
                            ActiveDirectoryGroupMember member = new ActiveDirectoryGroupMember();
                            member.GroupName    = groupName;
                            member.GroupMember  = ParseString(values);
                            member.MemberString = values.ToString();
                            group.Add(member);
                        }
                    }
                }
                if (group != null)
                {
                    _groupsCollection.Add(group);
                }
            }
        }
        // GET: Search
        public ActionResult Index()
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain);

            // Security grupları için (Query By Example - QBE)
            GroupPrincipal qbeGroup = new GroupPrincipal(context);

            qbeGroup.IsSecurityGroup = true;

            PrincipalSearcher search = new PrincipalSearcher(qbeGroup);

            // Bulunan grupların tutulacağı liste
            var groups = new List <ActiveDirectoryGroup>();

            foreach (var found in search.FindAll())
            {
                ActiveDirectoryGroup currentGroup = new ActiveDirectoryGroup();
                currentGroup.groupName       = found.Name;
                currentGroup.isSecurityGroup = true;
                groups.Add(currentGroup);
            }

            // Mail grupları için
            qbeGroup.IsSecurityGroup = false;

            search = new PrincipalSearcher(qbeGroup);

            foreach (var found in search.FindAll())
            {
                ActiveDirectoryGroup currentGroup = new ActiveDirectoryGroup();
                currentGroup.groupName = found.Name;
                groups.Add(currentGroup);
            }

            return(View(groups));
        }
Exemplo n.º 17
0
 public static void AddOrUpdate(ActiveDirectoryGroup group) => _addSubject.OnNext(group);
Exemplo n.º 18
0
        /// <summary>
        /// 判断域中是否存在指定的用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="ad"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        public bool HasUser(User user, ActiveDirectory ad, ActiveDirectoryGroup group)
        {
            var userDir = GetUser(user, ad, group);

            return(userDir != null);
        }
Exemplo n.º 19
0
 private static string GetOU(ActiveDirectoryGroup group)
 {
     return(group.OrganizationUnits);
 }
Exemplo n.º 20
0
        public IActionResult authTest(LoginRequestAuth login)
        {
            ActiveDirectoryUser user = null;

            if (login == null)
            {
                return(BadRequest(new ApiErrorResponse(HttpStatusCode.BadRequest, "Los parámetros del loging no son opcionales")));
            }
            try
            {
                //var res = ActiveDirectoryService.User_Logon(login.username, login.password, login.domain);
                var res = new LoogonUserResult();
                res.Autenticated = true;
                if (res.Autenticated)
                {
                    if (login.includeDomainUserData)
                    {
                        try
                        {
                            //user = ActiveDirectoryService.User_Info(login.username, login.domain);
                            user              = new ActiveDirectoryUser();
                            user.Company      = "contoso";
                            user.Country      = "arg";
                            user.FirstName    = login.username;
                            user.LoginName    = login.username;
                            user.EmailAddress = login.username + "@contoso.co";
                        }
                        catch (Exception ex)
                        {
                            res.ErrorMessage = "No fué posible obtener datos del usuario en el dominio. Razon =  " + ex.Message;
                        }
                    }


                    List <ActiveDirectoryGroup> userGroups = null;
                    if (login.includeGroups)
                    {
                        try
                        {
                            userGroups = new List <ActiveDirectoryGroup>();
                            ActiveDirectoryGroup g = new ActiveDirectoryGroup();
                            g.CN          = "co";
                            g.Description = "co";
                            g.Name        = "contoso";
                            userGroups.Add(g);
                        }
                        catch (Exception ex)
                        {
                            res.ErrorMessage = "No fué posible obtener los grupos usuario en el dominio. Razon =  " + ex.Message;
                        }
                    }


                    var jwt = TokenGenerator.GenerateTokenJwt_test(login.username, user, userGroups);

                    res.Token = jwt;
                }

                return(Ok(res));
            }
            catch (Exception ex)
            {
                var msg = apiHelper.getMessageException(ex);
                return(BadRequest(new ApiErrorResponse(HttpStatusCode.InternalServerError, msg)));
            }
        }