Пример #1
0
 public string ConnectToLDAP() {
     List<string> props = new List<string>();
     props.Add("cn");
     AuthenticationType = AuthenticationTypes.Secure;
     type = LdapService.ActiveDirectory;
     return Connect(userName, "(SAMAccountName=" + userName + ")", props);
 }
Пример #2
0
        /// <summary>
        /// Rename AD user.
        /// </summary>
        /// <param name="ldapConnectionInfo">Properties to define LDAP connection</param>
        /// <param name="userProperties">Properties to define the user to be renamed</param>
        /// <returns>operationSuccessful = true if operation is ok.</returns>
        public static OutputUser AD_RenameUser([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] AD_RenameUserProperties userProperties)
        {
            var ldapOperationResult = new OutputUser {
                OperationSuccessful = false, User = null
            };

            List <DirectoryEntry> tmpObjectEntries;

            ldapConnectionInfo.LdapUri = ldapConnectionInfo.LdapUri + "/" + userProperties.Path;

            var filter = "(&(objectClass=user)(cn=" + userProperties.Cn + "))";

            // @"(&(objectClass=user)(cn=MattiMeikalainen))
            using (var ldap = new LdapService(ldapConnectionInfo))
            {
                tmpObjectEntries = ldap.SearchObjectsByFilter(filter);
                if (tmpObjectEntries.Count == 1)
                {
                    ldapOperationResult.User = ldap.RenameAdUser(tmpObjectEntries[0], userProperties.NewCn);
                }
                else if (tmpObjectEntries.Count == 0)
                {
                    throw new Exception($"Did not find any entries matching filter {filter} from {ldapConnectionInfo.LdapUri}");
                }
                else if (tmpObjectEntries.Count > 1)
                {
                    throw new Exception($"Found more than one entry matching filter {filter} from {ldapConnectionInfo.LdapUri}");
                }
            }

            ldapOperationResult.OperationSuccessful = true;
            return(ldapOperationResult);
        }
Пример #3
0
        /// <summary>
        /// Searches Active Directory for objects specified by the given Path + filter, included in the AD_SearchObjectProperties class.
        /// </summary>
        /// <param name="ldapConnectionInfo">The LDAP connection information</param>
        /// <param name="SearchParameters">Path, filter and returned properties needed for the query</param>
        /// <returns>LdapResult class: the Collection of the SearchEntry classes.</returns>
        public static List <OutputSearchEntry> AD_SearchObjects([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] AD_SearchObjectProperties SearchParameters)
        {
            var ldapQueryInfo = new LdapConnectionInfo
            {
                LdapUri  = ldapConnectionInfo.LdapUri + "/" + SearchParameters.Path,
                Username = ldapConnectionInfo.Username,
                Password = ldapConnectionInfo.Password
            };

            List <SearchResult> tmpObjectEntries;

            // Search objects.
            using (var ldap = new LdapService(ldapQueryInfo))
                tmpObjectEntries = ldap.SearchObjectsByFilterSpecifyProperties(SearchParameters.Filter, SearchParameters.PropertiesToLoad, SearchParameters.PageSize);

            // Create & return result list.
            var retOutputs = new List <OutputSearchEntry>();

            foreach (var item in tmpObjectEntries)
            {
                var outputClass = new OutputSearchEntry
                {
                    SearchEntry = item
                };
                retOutputs.Add(outputClass);
            }
            return(retOutputs);
        }
Пример #4
0
        public void SyncFromLdap()
        {
            var sites      = LdapService.GetSites();
            var sitesAdded = DataService.InsertSitesData(sites);

            var depts      = LdapService.GetDepartments();
            var deptsAdded = DataService.InsertDepartmentsData(depts);

            var employees = LdapService.GetEmployees();
            var empsAdded = DataService.InsertEmployeesData(employees);

            var userGroups  = LdapService.GetGroups();
            var groupsAdded = DataService.InsertGroupsData(userGroups);

            var userMappings = new List <GroupMappingDTO>();

            userGroups.ToList().ForEach(g =>
            {
                var mappings = g.MemberLogins.Select(m => new GroupMappingDTO {
                    EmployeeLogin = m, GroupId = g.Id
                });
                userMappings.AddRange(mappings.ToList());
            });
            var mappingsAdded = DataService.InsertGroupMappings(userMappings);

            var deptManagers  = LdapService.GetDepartmentManagers();
            var deptMgrsAdded = DataService.InsertDeptManagers(deptManagers);
        }
Пример #5
0
        private async Task AddAsync()
        {
            try
            {
                if (!Groups.Any(x => x.Checked))
                {
                    WarningMessage = "Please select at least one group.";
                    return;
                }

                await LdapService.AddGroupsAsync(Groups.Where(x => x.Checked).ToList(), CreateEmployees);

                await ToastService.ShowToastAsync("Groups added.", ToastType.Success);

                await SynchronizationService.UpdateGroups(ExceptPageId);

                await ModalDialogService.CloseAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);

                await ModalDialogService.CancelAsync();
            }
        }
Пример #6
0
        private async Task AddAsync()
        {
            try
            {
                if (!Users.Any(x => x.Checked))
                {
                    WarningMessage = "Please select at least one user.";
                    return;
                }

                await LdapService.AddUsersAsync(Users.Where(x => x.Checked).ToList(), CreateAccounts, CreateGroups);

                await ToastService.ShowToastAsync("Employee imported.", ToastType.Success);

                //await HubContext.Clients.AllExcept(ConnectionId).SendAsync(RefreshPage.Employees);
                await ModalDialogService.CloseAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);

                await ModalDialogService.CancelAsync();
            }
        }
Пример #7
0
        public IActionResult Login(string username, string password)
        {
            try
            {
                LdapService _ldapService = new LdapService(_ldapconfig);
                var         appUser      = _ldapService.Login(username, password);

                if (appUser != null && appUser.IsAuthenticated)
                {
                    // insert user
                    if (!_eventsRepo.UserExists(username))
                    {
                        _eventsRepo.SaveUser(username, "");
                    }

                    Response.StatusCode = 200;
                    return(Ok(Response.StatusCode));
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
Пример #8
0
        protected void BtnBuscarUsuario_Click(object sender, EventArgs e)
        {
            try
            {
                if (TxUsuario.Text == String.Empty)
                {
                    throw new Exception("Ingrese un usuario para proceder con la busqueda.");
                }

                LdapService vLdap  = new LdapService();
                DataTable   vDatos = vLdap.GetDatosUsuario(ConfigurationManager.AppSettings["ADHOST"], TxUsuario.Text);

                if (vDatos.Rows.Count > 0)
                {
                    TxCorreo.Text    = vDatos.Rows[0]["mail"].ToString();
                    TxNombres.Text   = vDatos.Rows[0]["givenName"].ToString();
                    TxApellidos.Text = vDatos.Rows[0]["sn"].ToString();
                }
                else
                {
                    TxCorreo.Text    = String.Empty;
                    TxNombres.Text   = string.Empty;
                    TxApellidos.Text = String.Empty;
                    throw new Exception("No existe el usuario buscado");
                }
            }
            catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); }
        }
Пример #9
0
        private async Task <bool> VerifyAdUserAsync()
        {
            try
            {
                await LdapService.VerifyAdUserAsync(Employee);

                return(true);
            }
            catch (HESException ex) when(ex.Code == HESCode.ActiveDirectoryUserNotFound)
            {
                await EmployeeService.RemoveFromHideezKeyOwnersAsync(Employee.Id);

                Employee = await EmployeeService.GetEmployeeByIdAsync(EmployeeId, asNoTracking : true);

                await ToastService.ShowToastAsync(ex.Message, ToastType.Notify);

                return(false);
            }
            catch (LdapException ex) when(ex.ResultCode == (LdapForNet.Native.Native.ResultCode) 81)
            {
                await ToastService.ShowToastAsync("The LDAP server is unavailable.", ToastType.Error);

                return(false);
            }
            catch (Exception ex)
            {
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);

                return(false);
            }
        }
Пример #10
0
        private async Task EditAccountPasswordAsync()
        {
            try
            {
                await ButtonSpinner.SpinAsync(async() =>
                {
                    using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        await EmployeeService.EditPersonalAccountPwdAsync(Account, AccountPassword);

                        if (AccountPassword.UpdateActiveDirectoryPassword)
                        {
                            await LdapService.SetUserPasswordAsync(Account.EmployeeId, AccountPassword.Password, LdapSettings);
                        }

                        transactionScope.Complete();
                    }

                    RemoteDeviceConnectionsService.StartUpdateHardwareVaultAccounts(await EmployeeService.GetEmployeeVaultIdsAsync(Account.EmployeeId));
                    await ToastService.ShowToastAsync("Account password updated.", ToastType.Success);
                    await ModalDialogClose();
                });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);
                await ModalDialogClose();
            }
        }
Пример #11
0
        void getResponsables(String vIdInforme)
        {
            try{
                LdapService vLdap              = new LdapService();
                String      vQuery             = "[ACSP_ObtenerUsuariosInforme] 1," + vIdInforme;
                DataTable   vDatosResponsables = vConexion.obtenerDataTable(vQuery);

                DDLHallazgoResponsable.Items.Clear();
                DDLModificarHallazgosResponsable.Items.Clear();
                DDLHallazgoResponsable.Items.Add(new ListItem {
                    Value = "0", Text = "Seleccione un estado"
                });
                DDLModificarHallazgosResponsable.Items.Add(new ListItem {
                    Value = "0", Text = "Seleccione un estado"
                });
                foreach (DataRow item in vDatosResponsables.Rows)
                {
                    DDLHallazgoResponsable.Items.Add(new ListItem {
                        Value = item["idUsuario"].ToString(), Text = vConexion.GetNombreUsuario(item["idUsuario"].ToString())
                    });
                    DDLModificarHallazgosResponsable.Items.Add(new ListItem {
                        Value = item["idUsuario"].ToString(), Text = vConexion.GetNombreUsuario(item["idUsuario"].ToString())
                    });
                }
            }
            catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); }
        }
Пример #12
0
        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            try{
                LdapService vLdap = new LdapService();
                //Boolean vLogin = vLdap.ValidateCredentials(ConfigurationManager.AppSettings["ADHOST"], TxUsername.Text, TxPassword.Text);
                Boolean vLogin = true;

                if (vLogin)
                {
                    DataTable vDatos = new DataTable();
                    vDatos = vConexion.obtenerDataTable("ACSP_Login '" + TxUsername.Text + "'");

                    foreach (DataRow item in vDatos.Rows)
                    {
                        Session["AUTHCLASS"]     = vDatos;
                        Session["USUARIO"]       = item["idUsuario"].ToString();
                        Session["TIPOUSUARIO"]   = item["tipoUsuario"].ToString();
                        Session["JEFEAUDITORIA"] = item["jefeAuditoria"].ToString();

                        Session["AUTH"] = true;
                        Response.Redirect("/default.aspx");
                    }
                }
                else
                {
                    Session["AUTH"] = false;
                    throw new Exception("Usuario o contraseña incorrecta.");
                }
            }catch (Exception Ex) {
                LbMensaje.Text = "Usuario o contraseña incorrecta.";
                String vErrorLog = Ex.Message;
            }
        }
Пример #13
0
        private async Task SaveSettingsAsync()
        {
            try
            {
                var isValid = LdapSettingsContext.Validate();

                if (!isValid)
                {
                    return;
                }

                await LdapService.ValidateCredentialsAsync(LdapSettings);

                await AppSettingsService.SetLdapSettingsAsync(LdapSettings);

                await ToastService.ShowToastAsync("Domain settings updated.", ToastType.Success);
                await ModalDialogClose();
            }
            catch (LdapForNet.LdapInvalidCredentialsException)
            {
                ValidationErrorMessage.DisplayError(nameof(LdapSettings.Password), "Invalid password");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);
                await ModalDialogCancel();
            }
        }
Пример #14
0
        public ActionResult Index()
        {
            try
            {
                ViewBag.Error = false;
                var tempData = (MessageVM)TempData["UserMessage"];
                TempData["UserMessage"] = tempData;
                ViewBag.DisplayName     = Thread.CurrentPrincipal.Identity.Name;
                if (ViewBag.Path != null)
                {
                    m_LdapService = new LdapService(ViewBag.Path);
                    var usuario = m_LdapService.Search();
                    ViewBag.DisplayName = usuario.Nome;
                    return(View(usuario));
                }

                return(View());
            }
            catch (Exception ex)
            {
                ViewBag.Error           = true;
                TempData["UserMessage"] = new MessageVM()
                {
                    CssClassName = "alert-error", Title = "Erro", Message = ex.Message
                };
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return(View());
            }
        }
Пример #15
0
        private async Task GenerateAccountPasswordAsync()
        {
            try
            {
                if (LdapSettings?.Password == null)
                {
                    throw new Exception("Active Directory credentials not set in parameters page.");
                }

                var accountPassword = new AccountPassword()
                {
                    Password = PasswordGenerator.Generate()
                };

                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    await EmployeeService.EditPersonalAccountPwdAsync(Account, accountPassword);

                    await LdapService.SetUserPasswordAsync(Account.EmployeeId, accountPassword.Password, LdapSettings);

                    transactionScope.Complete();
                }

                RemoteDeviceConnectionsService.StartUpdateHardwareVaultAccounts(await EmployeeService.GetEmployeeVaultIdsAsync(Account.EmployeeId));
                await ToastService.ShowToastAsync("Account password updated.", ToastType.Success);
                await ModalDialogClose();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                await ToastService.ShowToastAsync(ex.Message, ToastType.Error);
                await ModalDialogCancel();
            }
        }
        /// <summary>
        /// Delete AD user.
        /// </summary>
        /// <param name="ldapConnectionInfo">Properties to define LDAP connection</param>
        /// <param name="userProperties">Properties to define the user to be deleted</param>
        /// <returns>operationSuccessful = true if operation is ok.</returns>
        public static Output AD_DeleteUser([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] AD_DeleteUserProperties userProperties)
        {
            var ret_output = new Output();
            List <DirectoryEntry> tmpObjectEntries;

            ret_output.operationSuccessful = false;

            ldapConnectionInfo.LdapUri = ldapConnectionInfo.LdapUri + "/" + userProperties.Path;

            string filter = "(&(objectClass=user)(cn=" + userProperties.Cn + "))";

            using (var ldap = new LdapService(ldapConnectionInfo))// @"(&(objectClass=user)(cn=MattiMeikalainen))
            {
                tmpObjectEntries = ldap.SearchObjectsByFilter(filter);
                if (tmpObjectEntries.Count > 0)
                {
                    ldap.DeleteAdUser(tmpObjectEntries[0]);
                }
                else
                {
                    throw new System.Exception($"Did not find any entries matching filter {filter} from {ldapConnectionInfo.LdapUri}");
                }
            }

            ret_output.operationSuccessful = true;
            return(ret_output);
        }
Пример #17
0
 public AccountController(SignInManager <ApplicationUser> signInManager, UserManagementService userService, UserManager <ApplicationUser> userManager, LdapService ldapService)
 {
     _signInManager = signInManager;
     _userService   = userService;
     _userManager   = userManager;
     _ldapService   = ldapService;
 }
Пример #18
0
 public HomeController()
 {
     ViewBag.Path = WebConfigurationManager.AppSettings["LdapPath"];
     if (ViewBag.Path != null)
     {
         m_LdapService = new LdapService(ViewBag.Path);
     }
 }
Пример #19
0
        /// <summary>
        /// Remove AD object from a set of groups.
        /// </summary>
        /// <param name="ldapConnectionInfo"></param>
        /// <param name="target"></param>
        /// <param name="groupsToRemoveFrom"></param>
        /// <returns>Object { bool operationSuccessful }</returns>
        public static Output AD_RemoveFromGroups([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] AD_RemoveFromGroupsTargetProperties target, [PropertyTab] AD_RemoveFromGroupsGroupProperties groupsToRemoveFrom)
        {
            var result = new Output();

            using (var ldap = new LdapService(ldapConnectionInfo)) result.OperationSuccessful = ldap.RemoveFromGroups(target.Dn, groupsToRemoveFrom.Groups);

            return(result);
        }
Пример #20
0
        public string ConnectToOpenLDAP()
        {
            List <string> props = new List <string>();

            props.Add("cn");
            AuthenticationType = AuthenticationTypes.None;
            type = LdapService.OpenLDAP;
            return(Connect(openLdapUserName, "(objectClass=*)", props));
        }
Пример #21
0
        public string ConnectToLDAP()
        {
            List <string> props = new List <string>();

            props.Add("cn");
            AuthenticationType = AuthenticationTypes.Secure;
            type = LdapService.ActiveDirectory;
            return(Connect(userName, "(SAMAccountName=" + userName + ")", props));
        }
Пример #22
0
 public LDAPHandler(string server, string rootDomain, string userName, string passWord) {
     this.serverName = server;
     this.rootDomain = rootDomain;
     this.userName = userName;
     this.openLdapUserName = "******" + userName + "," + rootDomain;
     this.passWord = passWord;
     this.isLoggedIn = false;
     this.type = LdapService.None;
 }
Пример #23
0
        public RadiusRouter(Configuration configuration, IRadiusPacketParser packetParser, ILogger logger)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _packetParser  = packetParser ?? throw new ArgumentNullException(nameof(packetParser));
            _logger        = logger ?? throw new ArgumentNullException(nameof(logger));

            _multifactorApiClient   = new MultiFactorApiClient(configuration, logger);
            _activeDirectoryService = new ActiveDirectoryService(configuration, logger);
            _ldapService            = new LdapService(configuration, logger);
        }
Пример #24
0
        public void Setup()
        {
            _settingsService = Substitute.For <SettingsService>((IServiceProvider)null);
            _certService     = Substitute.For <CertificateValidationService>(_settingsService);
            _ldap            = Substitute.For <LdapAuthWrapper>();

            _service = new LdapService(_settingsService, _certService, _ldap);

            _settingsService.Ldap_Enable.Returns(false);
        }
Пример #25
0
 public LDAPHandler(string server, string rootDomain, string userName, string passWord)
 {
     this.serverName       = server;
     this.rootDomain       = rootDomain;
     this.userName         = userName;
     this.openLdapUserName = "******" + userName + "," + rootDomain;
     this.passWord         = passWord;
     this.isLoggedIn       = false;
     this.type             = LdapService.None;
 }
 public AccountController(
     UserManager <AppUser> userManager,
     SignInManager <AppUser> signInManager,
     IIdentityServerInteractionService interactionService,
     LdapService ldap)
 {
     this.userManager        = userManager;
     this.signInManager      = signInManager;
     this.interactionService = interactionService;
     this.ldap = ldap;
 }
        public void getUsuariosResponsables()
        {
            try{
                LdapService vLdap    = new LdapService();
                String      vQuery   = "[ACSP_ObtenerUsuarios] 8";
                DataTable   vDatosDB = vConexion.obtenerDataTable(vQuery);

                DataTable vDatosFinal = new DataTable();
                vDatosFinal.Columns.Add("usuario");
                vDatosFinal.Columns.Add("nombre");
                vDatosFinal.Columns.Add("apellido");
                vDatosFinal.Columns.Add("correo");
                vDatosFinal.Columns.Add("empresa");
                vDatosFinal.Columns.Add("perfil");

                for (int i = 0; i < vDatosDB.Rows.Count; i++)
                {
                    DataTable vDatosAD = vLdap.GetDatosUsuario(ConfigurationManager.AppSettings["ADHOST"], vDatosDB.Rows[i]["idUsuario"].ToString());
                    if (vDatosAD.Rows.Count > 0)
                    {
                        vDatosFinal.Rows.Add(
                            vDatosDB.Rows[i]["idUsuario"].ToString(),
                            vDatosAD.Rows[0]["givenName"].ToString(),
                            vDatosAD.Rows[0]["sn"].ToString(),
                            vDatosAD.Rows[0]["mail"].ToString());
                        vDatosFinal.Rows[i]["empresa"] = vDatosDB.Rows[i]["empresa"].ToString();
                        vDatosFinal.Rows[i]["perfil"]  = vDatosDB.Rows[i]["perfil"].ToString();
                    }
                    else
                    {
                        vDatosFinal.Rows.Add(
                            vDatosDB.Rows[i]["idUsuario"].ToString(),
                            "",
                            "",
                            vDatosDB.Rows[i]["correo"].ToString());
                        vDatosFinal.Rows[i]["empresa"] = vDatosDB.Rows[i]["empresa"].ToString();
                        vDatosFinal.Rows[i]["perfil"]  = vDatosDB.Rows[i]["perfil"].ToString();
                    }
                }

                DDLUserResponsable.Items.Add(new ListItem {
                    Value = "0", Text = "Seleccione un usuario"
                });
                foreach (DataRow item in vDatosFinal.Rows)
                {
                    DDLUserResponsable.Items.Add(new ListItem {
                        Value = item["usuario"].ToString(), Text = item["nombre"].ToString() + " " + item["apellido"].ToString() + " - " + item["empresa"].ToString() + " - " + item["perfil"].ToString()
                    });
                }
                DDLUserResponsable.DataBind();
            }
            catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); }
        }
        /// <summary>
        /// Add the user in AD to group(s).
        /// </summary>
        /// <param name="ldapConnectionInfo"></param>
        /// <param name="User"></param>
        /// <param name="GroupsToAdd"></param>
        /// <returns></returns>
        public static Output AD_AddGroups([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] AD_AddGroupsUserProperties User, [PropertyTab] AD_AddGroupsProperties GroupsToAdd)
        {
            var ldapOperationResult = new Output {
                operationSuccessful = false
            };

            using (var ldap = new LdapService(ldapConnectionInfo))
            {
                ldapOperationResult.operationSuccessful = ldap.AddAdUserToGroup(User.dn, GroupsToAdd.groups);

                return(ldapOperationResult);
            }
        }
        /// <summary>
        /// Update a user in the AD.
        /// </summary>
        /// <param name="ldapConnectionInfo">The LDAP connection information</param>
        /// <param name="adUser">The user record to be updated</param>
        /// <returns>LdapResult class, which carries a copy of the updated user record.</returns>
        public static OutputUser AD_UpdateUser([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] UpdateADuser adUser)
        {
            var ldapOperationResult = new OutputUser {
                operationSuccessful = false, user = null
            };

            using (var ldap = new LdapService(ldapConnectionInfo))
            {
                ldapOperationResult.user = ldap.UpdateAdUser(adUser);
                ldapOperationResult.operationSuccessful = true;

                return(ldapOperationResult);
            }
        }
Пример #30
0
        /// <summary>
        /// Move a object to another OU (Organizational Unit). Returns class, which carries a copy of the updated object.
        /// </summary>
        /// <param name="ldapConnectionInfo"></param>
        /// <param name="adObject"></param>
        /// <returns>Object { DirectoryEntry ObjectEntryCopy }</returns>
        public static MoveAdObjectResult AD_MoveObject([PropertyTab] LdapConnectionInfo ldapConnectionInfo, [PropertyTab] MoveObject adObject)
        {
            var result = new MoveAdObjectResult
            {
                OperationSuccessful = false
            };

            using (var ldap = new LdapService(ldapConnectionInfo))
            {
                result.ObjectEntryCopy     = ldap.MoveAdObject(adObject);
                result.OperationSuccessful = true;
            }

            return(result);
        }
Пример #31
0
        /// <summary>
        /// Authenticate request at LDAP/Active Directory Domain with user-name and password
        /// </summary>
        private async Task <PacketCode> ProcessLdapAuthentication(PendingRequest request, ClientConfiguration clientConfig)
        {
            var userName = request.RequestPacket.UserName;
            var password = request.RequestPacket.UserPassword;

            if (string.IsNullOrEmpty(userName))
            {
                _logger.Warning("Can't find User-Name in message id={id} from {host:l}:{port}", request.RequestPacket.Identifier, request.RemoteEndpoint.Address, request.RemoteEndpoint.Port);
                return(PacketCode.AccessReject);
            }

            if (string.IsNullOrEmpty(password))
            {
                _logger.Warning("Can't find User-Password in message id={id} from {host:l}:{port}", request.RequestPacket.Identifier, request.RemoteEndpoint.Address, request.RemoteEndpoint.Port);
                return(PacketCode.AccessReject);
            }

            LdapService _service;

            switch (clientConfig.FirstFactorAuthenticationSource)
            {
            case AuthenticationSource.ActiveDirectory:
                _service = new ActiveDirectoryService(_serviceConfiguration, _logger);
                break;

            case AuthenticationSource.Ldap:
                _service = new LdapService(_serviceConfiguration, _logger);
                break;

            default:
                throw new NotImplementedException(clientConfig.FirstFactorAuthenticationSource.ToString());
            }

            //check all hosts
            var ldapUriList = clientConfig.ActiveDirectoryDomain.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var ldapUri in ldapUriList)
            {
                var isValid = await _service.VerifyCredential(userName, password, ldapUri, request, clientConfig);

                if (isValid)
                {
                    return(PacketCode.AccessAccept);
                }
            }

            return(PacketCode.AccessReject);
        }
Пример #32
0
 private async Task SyncAsync()
 {
     try
     {
         await LdapService.SyncUsersAsync(LdapSettings);
         await LdapService.ChangePasswordWhenExpiredAsync(LdapSettings);
         await ToastService.ShowToastAsync("Users synced.", ToastType.Success);
         await ModalDialogClose();
     }
     catch (Exception ex)
     {
         Logger.LogError(ex.Message);
         await ToastService.ShowToastAsync(ex.Message, ToastType.Error);
         await ModalDialogCancel();
     }
 }
Пример #33
0
 public string ConnectToOpenLDAP() {
     List<string> props = new List<string>();
     props.Add("cn");
     AuthenticationType = AuthenticationTypes.None;
     type = LdapService.OpenLDAP;
     return Connect(openLdapUserName, "(objectClass=*)", props);
 }
Пример #34
0
        private string Connect(string username, string filter, List<string> propertiesToLoad) {
            try {
                connection = new DirectoryEntry(FullURL, username, passWord);
                connection.AuthenticationType = AuthenticationType;

                //Object obj = connection.NativeObject;

                DirectorySearcher search = new DirectorySearcher(connection);
                search.SearchScope = SearchScope.Subtree;
                search.Filter = filter;
                if (propertiesToLoad != null) {
                    foreach (string s in propertiesToLoad) search.PropertiesToLoad.Add(s);
                }
                SearchResult result = search.FindOne();

                if(result == null) {
                    type = LdapService.None;
                    this.isLoggedIn = false;
                    return "Logon failure: Unrecognized username!";
                }

                this.isLoggedIn = true;
                
                return "Authenticated as "+result.Path;
                
            } catch (Exception e) {
                type = LdapService.None;
                this.isLoggedIn = false;
                return e.Message;
            }
        }