示例#1
0
        private SearchRequest GetSearchQuery(string distinguishedUserName)
        {
            userName = LdapHelper.GetCurrentLoggedInUse();
            string ldapUserQuery = string.Format(ldapUserFilter, userName);

            return(new SearchRequest(distinguishedUserName, ldapUserQuery, SearchScope.Subtree, null));
        }
 public async Task <LdapConnection> GetLdapConnection()
 {
     try
     {
         var flag = 0;
         _ldapConnectionUsers          = GetLDAPConnection();
         _ldapConnectionUsers.AuthType = AuthType.Basic;
         _ldapConnectionUsers.SessionOptions.SecureSocketLayer       = false;
         _ldapConnectionUsers.SessionOptions.ProtocolVersion         = 3;
         _ldapConnectionUsers.SessionOptions.VerifyServerCertificate =
             ServerCallback;
         _ldapConnectionUsers.SessionOptions.VerifyServerCertificate =
             (con, cer) => true;
         password = GetPasswordForUser();
         NetworkCredential network = LdapHelper.GetNetworkCredentials();
         LdapHelper.network           = network;
         _ldapConnectionUsers.Timeout = new TimeSpan(0, 0, 1, 0);
         _ldapConnectionUsers.Bind(network);
         Thread.Sleep(180000);
         return(_ldapConnectionUsers);
     }
     catch (Exception ex)
     {
     }
     return(_ldapConnectionUsers);
 }
示例#3
0
 public void GetUsers(List <string> groupDataForLDAP)
 {
     foreach (var groupData in groupDataForLDAP)
     {
         LdapHelper.GetUsersLdap(groupData);
     }
 }
示例#4
0
        public Form1()
        {
            InitializeComponent();

            try
            {
                textBoxPath.Text     = ConfigurationManager.AppSettings["Path"];
                textBoxAccount.Text  = ConfigurationManager.AppSettings["Account"];
                textBoxPassword.Text = ConfigurationManager.AppSettings["Password"];
                textBoxDn.Text       = ConfigurationManager.AppSettings["DistinguishedName"];

                ldapHelper = new LdapHelper(textBoxPath.Text, textBoxAccount.Text, textBoxPassword.Text);

                dtAttribute = new DataTable();
                dtAttribute.Columns.Add("Name");
                //dtAttribute.Columns.Add("Type");
                dtAttribute.Columns.Add("Value");
                dataGridViewAttribute.DataSource = dtAttribute;

                //attributeDictionary = new Dictionary<string, List<AttributeDataModel>>();
            }
            catch (Exception ex)
            {
                richTextBoxMessage.AppendText(ex.ToString());
            }
            finally
            {
                richTextBoxMessage.ScrollToCaret();
            }
        }
示例#5
0
 /// <summary>
 /// 构造方法
 /// </summary>
 public CurrentUser(ILogHelper <CurrentUser> logHelper, IRepository repo, IUser appUser, ICacheHelper cache, LdapHelper adHelper)
 {
     this.logHelper = logHelper;
     this.repo      = repo;
     this.appUser   = appUser;
     this.cache     = cache;
     this.adHelper  = adHelper;
 }
示例#6
0
 public LdapConnection GetLDAPConnection()
 {
     currentDomain =
         ((System.DirectoryServices.ActiveDirectory.ActiveDirectoryPartition)(Domain.GetCurrentDomain())).Name;
     //string str = GetNetbiosDomainName(currentDomain);
     // GetNetBiosName();
     currentDomain = "ad001.siemens.net";
     return(LdapHelper.GetLDAPConnection(currentDomain, defaultPort));
 }
示例#7
0
        /// <summary>
        /// Find by identity
        /// </summary>
        /// <param name="identityType">An IdentityType enumeration value that specifies the format of the identityValue parameter.</param>
        /// <param name="identityValue">The identity of the principal. This parameter can be any format that is contained in the IdentityType enumeration.</param>
        /// <returns></returns>
        public T FindByIdentity(IdentityType identityType, string identityValue)
        {
            if (string.IsNullOrEmpty(identityValue))
            {
                throw new ArgumentNullException(nameof(identityValue), "Identity value cannot be empty!");
            }

            return(LdapHelper.FindByIdentity <T>(Context, identityType, identityValue));
        }
示例#8
0
 public void GetNestedGroups(List <string> groupDataForLDAP)
 {
     //  LdapHelper.GetCurrentGroup();
     foreach (var groupData in groupDataForLDAP)
     {
         //LdapHelper.GetChildGroups(groupData, 0);
         //LdapHelper.GetParentGroups(groupData, 0);
         LdapHelper.GetMmbersOfGroup(groupData);
     }
 }
示例#9
0
        public IActionResult CreateToken([FromBody] LoginDto login)
        {
            IActionResult response = Unauthorized();

            if (login != null && LdapHelper.ValidateDomainCredentials(_unitOfWork, login.Username, login.Password))
            {
                var tokenString = BuildToken(login.Username);
                response = Ok(new { token = tokenString });
            }

            return(response);
        }
示例#10
0
        public void EncodeDecodePassword()
        {
            const string test_pass = "******";

            var passwordBytes = LdapHelper.GetPasswordBytes(test_pass);

            Assert.IsNotNull(passwordBytes);

            var strPass = LdapHelper.GetPassword(passwordBytes);

            Assert.AreEqual(strPass, test_pass);
        }
        private void RunSearchUser(string ldap, string netbios, int maxResultSet, string searchval)
        {
            try
            {
                DirectorySearcher searcher = new DirectorySearcher(GetDirectoryEntry(ldap));

                searcher.Filter = string.Format("(&(objectcategory=person)(objectclass=user)(|(sAMAccountName={0}*)(displayName={0}*)(mail={0}*)))", searchval);
                if (maxResultSet == 0)
                {
                    searcher.SizeLimit = base.ADMaxResultSize;
                }
                else
                {
                    searcher.SizeLimit = maxResultSet;
                }
                searcher.PropertiesToLoad.Add(AdProperties.SamlAccountName);
                searcher.PropertiesToLoad.Add(AdProperties.DisplayName);
                searcher.PropertiesToLoad.Add(AdProperties.Email);
                foreach (string prop in AdditionalADProps)
                {
                    searcher.PropertiesToLoad.Add(prop);
                }

                SearchResultCollection col = searcher.FindAll();

                DataTable results = base.ServiceBroker.ServicePackage.ResultTable;

                DataRow dr;
                string  saml;
                foreach (SearchResult res in col)
                {
                    dr = results.NewRow();

                    saml = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.SamlAccountName);
                    dr[Constants.SOProperties.ActiveDirectory.UserFQN]        = string.Concat(netbios, "\\", saml);
                    dr[Constants.SOProperties.ActiveDirectory.SamAccountName] = saml;
                    dr[Constants.SOProperties.ActiveDirectory.DisplayName]    = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.DisplayName);
                    dr[Constants.SOProperties.ActiveDirectory.Email]          = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.Email);
                    foreach (string prop in AdditionalADProps)
                    {
                        dr[prop] = LdapHelper.GetSingleStringPropertyCollectionValue(res.Properties, prop);
                    }
                    lock (base.ServiceBroker.ServicePackage.ResultTable)
                    {
                        results.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("Failed to query {0}", ldap), ex);
            }
        }
        protected void BindGroupsTab()
        {
            List <ADGroup> groups = new List <ADGroup>();

            try
            {
                groups = LdapHelper.GetADGroups(Request.LogonUserIdentity.Groups);
                userGroupsGrid.DataSource = groups;
                userGroupsGrid.DataBind();
            }
            catch (Exception gex)
            {
                ToggleMessage($"BindGroupsTab::{gex.ToString()}", true, true);
            }
        }
示例#13
0
        public async Task <IHttpActionResult> GetAllGroups()
        {
            try
            {
                string data = await Request.Content.ReadAsStringAsync();

                var query  = JsonConvert.DeserializeObject <LdapUserQuery>(data);
                var ldap   = new LdapHelper(query.Server);
                var groups = ldap.GetAllGroups();
                return(Ok(groups));
            }
            catch
            {
                return(NotFound());
            }
        }
示例#14
0
        public async Task <IHttpActionResult> AuthenticateUser()
        {
            try
            {
                string data = await Request.Content.ReadAsStringAsync();

                var  query  = JsonConvert.DeserializeObject <LdapUserQuery>(data);
                var  ldap   = new LdapHelper(query.Server);
                bool result = ldap.AuthenticateUser(query.LoginName, query.Password);
                return(Ok(result));
            }
            catch
            {
                return(NotFound());
            }
        }
示例#15
0
        public LdapConnection BindLDAPConnection()
        {
            var flag = 0;

            _ldapConnectionUsers          = GetLDAPConnection();
            _ldapConnectionUsers.AuthType = AuthType.Basic;
            _ldapConnectionUsers.SessionOptions.SecureSocketLayer       = true;
            _ldapConnectionUsers.SessionOptions.ProtocolVersion         = 3;
            _ldapConnectionUsers.SessionOptions.VerifyServerCertificate =
                ServerCallback;
            password = GetPasswordForUser();
            NetworkCredential network = LdapHelper.GetNetworkCredentials();

            LdapHelper.network           = network;
            _ldapConnectionUsers.Timeout = new TimeSpan(0, 0, 1, 0);
            _ldapConnectionUsers.Bind(network);
            return(_ldapConnectionUsers);
        }
        private void GetUserDetails()
        {
            string userfqn         = base.GetStringProperty(Constants.SOProperties.ActiveDirectory.UserFQN, true);
            string samlaccountname = userfqn.Substring(userfqn.IndexOf('\\') + 1);

            string[] ldaps = base.LDAPPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string ldap in ldaps)
            {
                DirectorySearcher searcher = new DirectorySearcher(GetDirectoryEntry(ldap));
                searcher.Filter   = string.Format("(&(objectcategory=person)(objectclass=user)(sAMAccountName={0}))", EscapeSearchFilter(samlaccountname));
                searcher.PageSize = base.ADMaxResultSize;

                SearchResult res = searcher.FindOne();
                if (res != null)
                {
                    ServiceObject serviceObject = base.ServiceBroker.Service.ServiceObjects[0];
                    serviceObject.Properties.InitResultTable();
                    DataTable results = base.ServiceBroker.ServicePackage.ResultTable;

                    DataRow dr = results.NewRow();

                    dr[Constants.SOProperties.ActiveDirectory.SamAccountName]     = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.SamlAccountName);
                    dr[Constants.SOProperties.ActiveDirectory.DisplayName]        = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.DisplayName);
                    dr[Constants.SOProperties.ActiveDirectory.CommonName]         = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.CommonName);
                    dr[Constants.SOProperties.ActiveDirectory.GivenName]          = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.GivenName);
                    dr[Constants.SOProperties.ActiveDirectory.Initials]           = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.Initials);
                    dr[Constants.SOProperties.ActiveDirectory.Surname]            = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.Surname);
                    dr[Constants.SOProperties.ActiveDirectory.Email]              = GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.Email);
                    dr[Constants.SOProperties.ActiveDirectory.OrganisationalUnit] = GetOUFromDistinguishedName(GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.DistinguishedName));
                    foreach (string prop in AdditionalADProps)
                    {
                        dr[prop] = LdapHelper.GetSingleStringPropertyCollectionValue(res.Properties, prop);
                    }

                    results.Rows.Add(dr);
                    break; // there can be only one as this is a read method.
                }
            }


            #endregion GetUserDetails
        }
示例#17
0
        public async Task <IHttpActionResult> GetUserByLogin()
        {
            try
            {
                string data = await Request.Content.ReadAsStringAsync();

                var query = JsonConvert.DeserializeObject <LdapUserQuery>(data);
                var ldap  = new LdapHelper(query.Server);
                var user  = ldap.GetUserByLogin(query.LoginName);
                if (user == null)
                {
                    throw new System.Exception($"Unable to find user: {query.LoginName}");
                }
                return(Ok(user));
            }
            catch
            {
                return(NotFound());
            }
        }
示例#18
0
        public void CallbackMethod(IAsyncResult ar)
        {
            AsyncResult       result = (AsyncResult)ar;
            AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;

            _ldapConnectionUsers = caller.EndInvoke(result);
            string distinguishedUserName = LdapHelper.GetCurrentUser(_ldapConnectionUsers, currentDomain);

            LdapHelper.SetLDAPConnection(_ldapConnectionUsers);
            LdapHelper.GetLdapGroupMembers("RG CN BSCE ALL");
            //LdapHelper.GetLdapGroupMembers("RG IN SL Siemens Learning Manager");
            //LdapHelper.GetLdapGroupMembers("RG IN STS BLR Bangalore Group2");
            // LdapHelper.GetLdapGroupMembers("RG IN STS SPIRIDON SAP USERS");
            //LdapHelper.GetLdapGroupMembers("DF FA SE DS FTH BR (IMD)");
            //Get parent groups
            SearchRequest searchRequest = GetSearchQuery(distinguishedUserName);


            GetGroups(searchRequest);
        }
示例#19
0
        // validates the user against the LDAP System and returns its propertues as a Dictionary
        public IActionResult CheckUserInLdapAndReturnAttributes(string username, string password)
        {
            var validCredentials = LdapHelper.ValidateCredentials(username, password);

            if (!validCredentials)
            {
                return(new BadRequestObjectResult("Wrong credentials"));
            }

            var ldapUserAttributes = LdapHelper.GetLdapUser(username);

            if (ldapUserAttributes == null)
            {
                return(new NotFoundObjectResult("User Not Found in LDAP"));
            }

            if (CheckIfUserAllreadyRegistered(ldapUserAttributes))
            {
                return(new BadRequestObjectResult("User Allready Registered"));
            }
            return(new OkObjectResult(ldapUserAttributes));
        }
示例#20
0
        public async Task <List <T> > CustomSearch <T>(ILdapConnection conn, string filter, IEnumerable <int> employeeIds = null, string path = "")
        {
            return(await Task.Run(() =>
            {
                var searchPath = string.Empty;
                if (string.IsNullOrEmpty(path))
                {
                    searchPath = _config.Path;
                }
                else
                {
                    searchPath = path;
                }

                var attrs = LdapHelper.GetLdapAttributes <T>().ToArray();
                var search = conn.Search(searchPath, LdapConnection.ScopeSub, filter, attrs, false);

                return LdapHelper.ConvertLdapResult <T>(_logger, search, employeeIds, (propName, attr) =>
                {
                    if (propName == "Photo")
                    {
                        byte[] picData = (byte[])(Array)attr.ByteValue;
                        return Convert.ToBase64String(picData);
                    }
                    else
                    {
                        if (attr.StringValueArray.Length > 1)
                        {
                            return attr.StringValueArray.ToList();
                        }
                        else
                        {
                            return attr.StringValue;
                        }
                    }
                });
            }));
        }
示例#21
0
        // creates a new user
        public IActionResult CreateUser(string rzName, string rzPassword, UserCreateDto user)
        {
            var rzNameData    = Convert.FromBase64String(rzName);
            var decodedRzname = Encoding.UTF8.GetString(rzNameData);

            var rzPasswordData  = Convert.FromBase64String(rzPassword);
            var decodedPassword = Encoding.UTF8.GetString(rzPasswordData);

            var ldapCredentialsAreValid = CheckIfLdapCredentialsAreValid(decodedRzname, decodedPassword);

            if (!ldapCredentialsAreValid)
            {
                return(new BadRequestObjectResult("Wrong Ldap Credentials"));
            }

            var ldapUserAsDictionary = LdapHelper.GetLdapUser(decodedRzname);
            var ldapIdOfUser         = Convert.ToInt32(ldapUserAsDictionary["uidNumber"]);

            var userAllreadyExists = CheckIfUserAllreadyExists(ldapIdOfUser, decodedRzname);

            if (userAllreadyExists)
            {
                return(new BadRequestObjectResult("User is allready registered"));
            }

            var newUser = user.ToModel();

            newUser.Firstname    = ldapUserAsDictionary["givenName"];
            newUser.Lastname     = ldapUserAsDictionary["sn"];
            newUser.EmployeeType = ldapUserAsDictionary["employeeType"];
            newUser.RzName       = ldapUserAsDictionary["uid"];
            newUser.LdapId       = Convert.ToInt32(ldapUserAsDictionary["uidNumber"]);

            _applicationDbContext.AppUser.Add(newUser);
            Save();

            return(new CreatedResult($"/users/{newUser.Id}", newUser.ToDetailDto()));
        }
        public LDAPUserImporter(LDAPSupportSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            _ldapHelper = !WorkContext.IsMono ? (LdapHelper) new SystemLdapHelper() : new NovellLdapHelper();

            _settings = DeepClone(settings);

            if (_settings.EnableLdapAuthentication)
            {
                if (string.IsNullOrEmpty(_settings.UserFilter) ||
                    _settings.GroupMembership && string.IsNullOrEmpty(_settings.GroupFilter))
                {
                    var defaultSettings = settings.GetDefault() as LDAPSupportSettings;

                    if (defaultSettings != null)
                    {
                        if (string.IsNullOrEmpty(_settings.UserFilter))
                        {
                            _settings.UserFilter = defaultSettings.UserFilter;
                        }

                        if (_settings.GroupMembership && string.IsNullOrEmpty(_settings.GroupFilter))
                        {
                            _settings.GroupFilter = defaultSettings.GroupFilter;
                        }
                    }
                }
            }

            AllDomainUsers  = new List <LDAPObject>();
            AllDomainGroups = new List <LDAPObject>();
        }
        public ISettings GetDefault()
        {
            var domainName        = "";
            var distinguishedName = "";

            var isMono = WorkContext.IsMono;

            if (!isMono)
            {
                try
                {
                    var domain = Domain.GetCurrentDomain();
                    domainName = string.Format(@"LDAP://{0}", domain.Name);

                    if (_ldapHelper == null)
                    {
                        _ldapHelper = new SystemLdapHelper();
                    }

                    distinguishedName =
                        _ldapHelper.GetDefaultDistinguishedName(domainName, Constants.STANDART_LDAP_PORT) ?? "";
                }
                catch (Exception)
                {
                    domainName        = "";
                    distinguishedName = "";
                }
            }

            var settings = new LDAPSupportSettings
            {
                Server     = domainName,
                UserDN     = distinguishedName,
                PortNumber = Constants.STANDART_LDAP_PORT,
                UserFilter = string.Format("({0}=*)",
                                           isMono
                        ? Constants.RfcLDAPAttributes.UID
                        : Constants.ADSchemaAttributes.USER_PRINCIPAL_NAME),
                LoginAttribute = isMono
                    ? Constants.RfcLDAPAttributes.UID
                    : Constants.ADSchemaAttributes.ACCOUNT_NAME,
                FirstNameAttribute   = Constants.ADSchemaAttributes.FIRST_NAME,
                SecondNameAttribute  = Constants.ADSchemaAttributes.SURNAME,
                MailAttribute        = Constants.ADSchemaAttributes.MAIL,
                TitleAttribute       = Constants.ADSchemaAttributes.TITLE,
                MobilePhoneAttribute = Constants.ADSchemaAttributes.MOBILE,
                LocationAttribute    = Constants.ADSchemaAttributes.STREET,
                GroupDN     = distinguishedName,
                GroupFilter = string.Format("({0}={1})", Constants.ADSchemaAttributes.OBJECT_CLASS,
                                            isMono
                        ? Constants.ObjectClassKnowedValues.POSIX_GROUP
                        : Constants.ObjectClassKnowedValues.GROUP),
                UserAttribute =
                    isMono
                        ? Constants.RfcLDAPAttributes.UID
                        : Constants.ADSchemaAttributes.DISTINGUISHED_NAME,
                GroupAttribute     = isMono ? Constants.RfcLDAPAttributes.MEMBER_UID : Constants.ADSchemaAttributes.MEMBER,
                GroupNameAttribute = Constants.ADSchemaAttributes.COMMON_NAME,
                Authentication     = string.IsNullOrEmpty(distinguishedName)
            };

            return(settings);
        }
 public LDAPSupportSettings()
 {
     _ldapHelper = !WorkContext.IsMono ? (LdapHelper) new SystemLdapHelper() : new NovellLdapHelper();
 }
        private void btnSyncDept_Click(object sender, RoutedEventArgs e)
        {
            ServerCommandProxy serverProxy;
            OperationTypeEnum  operation = OperationTypeEnum.SyncDepartment;

            txtblockOutput.Inlines.Clear();

            try
            {
                ValidationResult result = ValidateInput(operation);

                if (result.IsValid)
                {
                    string ppcHostname = txtboxPpcServer.Text;
                    string ppcAdminPw  = pwdboxPpcAdminPw.Password;

                    serverProxy = new ServerCommandProxy(ppcHostname, 9191, ppcAdminPw);

                    if (PaperCutProxyWrapper.IsConnectionEstablished(serverProxy))
                    {
                        txtblockOutput.Inlines.Add(Constants.PaperCut.Messages.PaperCutConnectionEstablished);

                        string domainName    = txtboxDomainName.Text;
                        string ldapRoot      = txtboxLdapRoot.Text;
                        string domainUser    = txtboxDomainUser.Text;
                        string domainUserPwd = pwdboxDomainUserPwd.Password;

                        LdapHelper ldapHelper = new LdapHelper(domainName, ldapRoot, domainUser, domainUserPwd);

                        if (ldapHelper.IsConnectionEstablished(domainUser))
                        {
                            txtblockOutput.Inlines.Add(Constants.Ldap.Messages.LdapConnectionEstablished);

                            PaperCutUser[] ppcUsers = PaperCutProxyWrapper.GetUsersDepartmentInfo(serverProxy);

                            int    targetDeptField         = cmboxTargetDeptField.SelectedIndex;
                            string departmentNameADField   = txtboxDeptNameADField.Text;
                            string departmentNumberADField = txtboxDeptNumberADField.Text;

                            bool areBothAdFieldsEntered = !string.IsNullOrEmpty(departmentNameADField) &&
                                                          !string.IsNullOrEmpty(departmentNumberADField);

                            if (areBothAdFieldsEntered)
                            {
                                LdapUser[] ldapUsers = ldapHelper.RetrieveDepartmentInformation(ppcUsers, departmentNameADField, departmentNumberADField);
                                PaperCutProxyWrapper.SetUsersMultipleDepartmentInfo(serverProxy, ldapUsers, targetDeptField);
                            }
                            else
                            {
                                LdapUser[] ldapUsers = ldapHelper.RetrieveDepartmentInformation(ppcUsers, string.IsNullOrEmpty(departmentNameADField) ?
                                                                                                departmentNumberADField : departmentNameADField);
                                PaperCutProxyWrapper.SetUsersSingleDepartmentInfo(serverProxy, ldapUsers, targetDeptField);
                            }
                        }
                        else
                        {
                            txtblockOutput.Inlines.Add(Constants.Ldap.Messages.LdapConnectionNotEstablished);
                        }
                    }
                    else
                    {
                        txtblockOutput.Inlines.Add(Constants.PaperCut.Messages.PaperCutConnectionNotEstablished);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#26
0
        public virtual async Task <UserLoginResult> TryLogin(LoginViewModel model)
        {
            var          template        = new LoginResultTemplate();
            IUserContext userContext     = null;
            LdapUser     ldapUser        = null;
            var          isFakeLdapEmail = false;

            if (UserManager.Site.UseEmailForLogin && !string.IsNullOrWhiteSpace(model.UserName) && model.UserName.IndexOf("@") > -1)
            {
                template.User = await UserManager.FindByEmailAsync(model.UserName);
            }

            if (template.User == null)
            {
                template.User = await UserManager.FindByNameAsync(model.UserName);
            }

            if (template.User == null || string.IsNullOrWhiteSpace(template.User.PasswordHash)) //no password on cloudscribe user so could be ldap
            {
                if (LdapHelper.IsImplemented && !string.IsNullOrWhiteSpace(UserManager.Site.LdapServer) && !string.IsNullOrWhiteSpace(UserManager.Site.LdapDomain))
                {
                    ldapUser = await LdapHelper.TryLdapLogin(UserManager.Site as ILdapSettings, model.UserName, model.Password);
                }
            }

            if (ldapUser != null) //ldap auth success
            {
                if (template.User == null)
                {
                    //ldap auth success but no siteuser exists so create one and sign in
                    var cloudscribeUser = new SiteUser()
                    {
                        SiteId          = UserManager.Site.Id,
                        UserName        = model.UserName,
                        Email           = ldapUser.Email,
                        DisplayName     = ldapUser.CommonName,
                        FirstName       = ldapUser.FirstName,
                        LastName        = ldapUser.LastName,
                        LastLoginUtc    = DateTime.UtcNow,
                        AccountApproved = true
                    };

                    if (string.IsNullOrWhiteSpace(cloudscribeUser.DisplayName))
                    {
                        cloudscribeUser.DisplayName = model.UserName;
                    }

                    if (string.IsNullOrWhiteSpace(cloudscribeUser.Email))
                    {
                        // identity doesn't allow create user with no email so fake it here then null it out below after sign in.
                        // the cloudscribe site rules middleware will then force the user to provide an email
                        cloudscribeUser.Email = model.UserName + "@fake-email.com";
                        isFakeLdapEmail       = true;
                    }

                    var createdResult = await UserManager.CreateAsync(cloudscribeUser);

                    if (createdResult.Succeeded)
                    {
                        template.User = cloudscribeUser;
                        await SignInManager.SignInAsync(cloudscribeUser, model.RememberMe);

                        template.SignInResult = SignInResult.Success;
                        if (isFakeLdapEmail)
                        {
                            // clear the fake email, the user should then be forced to provide an email by site rules middleware
                            cloudscribeUser.Email           = null;
                            cloudscribeUser.NormalizedEmail = null;
                            await UserCommands.Update(cloudscribeUser);
                        }
                    }
                }
                else
                {
                    //siteuser already created for ldap user so just sign in
                    await SignInManager.SignInAsync(template.User, model.RememberMe);

                    template.SignInResult = SignInResult.Success;
                }
            }

            if (template.User != null && ldapUser == null) //these rules don't apply for ldap users
            {
                await LoginRulesProcessor.ProcessAccountLoginRules(template);
            }

            if (template.User != null)
            {
                //this will get persisted if login succeeds
                template.User.BrowserKey = Guid.NewGuid().ToString();

                userContext = new UserContext(template.User);
            }

            if (userContext != null &&
                template.SignInResult == SignInResult.Failed &&
                template.RejectReasons.Count == 0)
            {
                var persistent = false;
                if (UserManager.Site.AllowPersistentLogin)
                {
                    persistent = model.RememberMe;
                }

                //template.SignInResult = await SignInManager.PasswordSignInAsync(
                //    model.UserName,
                //    model.Password,
                //    persistent,
                //    lockoutOnFailure: false);

                template.SignInResult = await SignInManager.PasswordSignInAsync(
                    template.User,
                    model.Password,
                    persistent,
                    lockoutOnFailure : false);


                if (template.SignInResult.Succeeded)
                {
                    //update last login time
                    template.User.LastLoginUtc = DateTime.UtcNow;

                    if (string.IsNullOrEmpty(template.User.SecurityStamp))
                    {
                        // if security stamp is empty then the securitystamp validation
                        // fails when it checks after 30 minutes
                        // users created via usermanager this gets populated but not
                        // populated for the admin user created by seeding data
                        // changes to the user such as password change also will populate it
                        // but we can go ahead and check here and populate it if it is empty
                        await UserManager.UpdateSecurityStampAsync(template.User);

                        if (template.User.PasswordHash == "admin||0")
                        {
                            // initial admin user has not updated the password, need to hash it
                            await UserManager.ChangeUserPassword(template.User, "admin", validatePassword : false);

                            await SignInManager.SignOutAsync();

                            // security stamp needs to be there before authentication to avoid the problem

                            template.SignInResult = await SignInManager.PasswordSignInAsync(
                                model.UserName,
                                model.Password,
                                persistent,
                                lockoutOnFailure : false);
                        }
                    }
                    else
                    {
                        await UserManager.UpdateAsync(template.User);
                    }
                }
            }

            return(new UserLoginResult(
                       template.SignInResult,
                       template.RejectReasons,
                       userContext,
                       template.IsNewUserRegistration,
                       template.MustAcceptTerms,
                       template.NeedsAccountApproval,
                       template.NeedsEmailConfirmation,
                       template.EmailConfirmationToken,
                       template.NeedsPhoneConfirmation
                       ));
        }
示例#27
0
        public bool IsMemberOf(IdentityType identityType, string identityValue, IdentityType groupIdentityType, string groupIdentityValue)
        {
            var principal = FindByIdentity(identityType, identityValue);

            return(principal.IsMemberOf(LdapHelper.FindByIdentity <GroupPrincipal>(Context, groupIdentityType, groupIdentityValue)));
        }
示例#28
0
 public PrincipalSearchResult <T> PrincipalSearch()
 {
     return(LdapHelper.PrincipalSearch <T>(Context));
 }
示例#29
0
 public SearchResultCollection Search(LdapSearchParameters parameters)
 {
     return(LdapHelper.FindAll(DirectoryEntry, string.Format(DefaultFilter, parameters.Filter), parameters.PropertiesToLoad, parameters.SortOption, parameters.PageSize, parameters.SizeLimit));
 }
示例#30
0
        private void PrepareSettings(LdapSettings settings)
        {
            if (settings == null)
            {
                Logger.Error("Wrong LDAP settings were received from client.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!settings.EnableLdapAuthentication)
            {
                settings.Password = string.Empty;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.Server))
            {
                settings.Server = settings.Server.Trim();
            }
            else
            {
                Logger.Error("settings.Server is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!settings.Server.StartsWith("LDAP://"))
            {
                settings.Server = "LDAP://" + settings.Server.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.UserDN))
            {
                settings.UserDN = settings.UserDN.Trim();
            }
            else
            {
                Logger.Error("settings.UserDN is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.LoginAttribute))
            {
                settings.LoginAttribute = settings.LoginAttribute.Trim();
            }
            else
            {
                Logger.Error("settings.LoginAttribute is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.UserFilter))
            {
                settings.UserFilter = settings.UserFilter.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.FirstNameAttribute))
            {
                settings.FirstNameAttribute = settings.FirstNameAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.SecondNameAttribute))
            {
                settings.SecondNameAttribute = settings.SecondNameAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.MailAttribute))
            {
                settings.MailAttribute = settings.MailAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.TitleAttribute))
            {
                settings.TitleAttribute = settings.TitleAttribute.Trim();
            }

            if (!string.IsNullOrWhiteSpace(settings.MobilePhoneAttribute))
            {
                settings.MobilePhoneAttribute = settings.MobilePhoneAttribute.Trim();
            }

            if (settings.GroupMembership)
            {
                if (!string.IsNullOrWhiteSpace(settings.GroupDN))
                {
                    settings.GroupDN = settings.GroupDN.Trim();
                }
                else
                {
                    Logger.Error("settings.GroupDN is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }

                if (!string.IsNullOrWhiteSpace(settings.GroupFilter))
                {
                    settings.GroupFilter = settings.GroupFilter.Trim();
                }

                if (!string.IsNullOrWhiteSpace(settings.GroupAttribute))
                {
                    settings.GroupAttribute = settings.GroupAttribute.Trim();
                }
                else
                {
                    Logger.Error("settings.GroupAttribute is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }

                if (!string.IsNullOrWhiteSpace(settings.UserAttribute))
                {
                    settings.UserAttribute = settings.UserAttribute.Trim();
                }
                else
                {
                    Logger.Error("settings.UserAttribute is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }
            }

            if (!settings.Authentication)
            {
                settings.Password = string.Empty;
                return;
            }

            if (!string.IsNullOrWhiteSpace(settings.Login))
            {
                settings.Login = settings.Login.Trim();
            }
            else
            {
                Logger.Error("settings.Login is null or empty.");
                Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                return;
            }

            if (settings.PasswordBytes == null || !settings.PasswordBytes.Any())
            {
                if (!string.IsNullOrEmpty(settings.Password))
                {
                    settings.PasswordBytes = LdapHelper.GetPasswordBytes(settings.Password);

                    if (settings.PasswordBytes == null)
                    {
                        Logger.Error("settings.PasswordBytes is null.");
                        Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                        return;
                    }
                }
                else
                {
                    Logger.Error("settings.Password is null or empty.");
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    return;
                }
            }

            settings.Password = string.Empty;
        }