public bool AuthenticateUser(string Domain, string Username, string Password, string LDAP_Path, ref string Errmsg) { Errmsg = ""; string domainAndUsername = Domain + "\\" + Username; DirectoryEntry entry = new DirectoryEntry(LDAP_Path, domainAndUsername, Password); entry.AuthenticationType = AuthenticationTypes.Secure; try { DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + Username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (result == null) { return false; } // Update the new path to the user in the directory LDAP_Path = result.Path; string _filterAttribute = (String)result.Properties["cn"][0]; } catch (Exception ex) { Errmsg = ex.Message; return false; throw new Exception("Error authenticating user." + ex.Message); } return true; }
public static void Main() { string path= "LDAP://DC=[DOMAIN],DC=local"; string strAccountId = "[USERNAME]"; string strPassword = "******"; bool bSucceeded; string strError; DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword); DirectorySearcher adsSearcher = new DirectorySearcher( adsEntry ); adsSearcher.Filter = "(sAMAccountName=" + strAccountId + ")"; try { SearchResult adsSearchResult = adsSearcher.FindOne(); bSucceeded = true; strError = "User has been authenticated by Active Directory."; adsEntry.Close(); } catch ( Exception ex ) { bSucceeded = false; strError = ex.Message; adsEntry.Close(); } if (bSucceeded){ Console.WriteLine("Great Success"); }else { Console.WriteLine("Great Fail"); } }
public string GetGroups() { DirectorySearcher search = new DirectorySearcher(_path); search.Filter = "(cn=" + _filterAttribute + ")"; search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; string dn; int equalsIndex, commaIndex; for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) { dn = (string)result.Properties["memberOf"][propertyCounter]; equalsIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalsIndex) { return null; } groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)); groupNames.Append("|"); } } catch (System.Exception ex) { throw new System.Exception("Error obtaining group names. " + ex.Message); } return groupNames.ToString(); }
public bool AuthenticateUser(string domain, string username, string password, string LdapPath, out string Errmsg) { Errmsg = ""; string domainAndUsername = domain + @"\" + username; DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password); try { // Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) { return false; } // Update the new path to the user in the directory LdapPath = result.Path; string _filterAttribute = (String)result.Properties["cn"][0]; } catch (Exception ex) { Errmsg = ex.Message; return false; throw new Exception("Error authenticating user." + ex.Message); } return true; }
public bool IsAuthenticated(string domain, string username, string pwd) { if (username == "esb" && pwd == "a") return true; string domainAndUsername = domain + @"\" + username; DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd); try { //Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (string)result.Properties["cn"][0]; } catch (System.Exception ex) { throw new System.Exception(" " + ex.Message); } return true; }
private void doADCopy(String username) { DirectoryEntry de = new DirectoryEntry("LDAP://ewprint.eastway.local/OU=Active Users,DC=eastway,DC=local"); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = "sAMAccountName=" + username; SearchResult sr = ds.FindOne(); DirectoryEntry user = sr.GetDirectoryEntry(); SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["EWEHR"].ToString()); try { cn.Open(); if (isEchartsUser(user.Properties["employeeNumber"].Value.ToString())) { SqlCommand cmd = new SqlCommand("UPDATE echarts_user set " + "office = '" + user.Properties["physicalDeliveryOfficeName"].Value + "', " + "office_phone = '" + user.Properties["telephoneNumber"].Value + "', " + "staff_description = '" + user.Properties["title"].Value + "', " + "staff_name = '" + user.Properties["displayName"].Value + "', " + "status = 'Active', " + "supervisor = '" + getManager(user.Properties["manager"].Value.ToString()) + "', " + "username = '******' " + "WHERE staff_id = '" + user.Properties["employeeNumber"].Value + "'", cn); if (cmd.ExecuteNonQuery() == 0) { Response.Write("UPDATE FAILED"); } else { HttpCookie staffid = new HttpCookie("staff_id"); staffid.Value = (String)user.Properties["employeeNumber"].Value; staffid.Expires = DateTime.UtcNow.AddMonths(6); staffid.Domain = EchartsAuth.domainName; Response.Cookies.Add(staffid); doRedirect(Request.QueryString["continue"]); } } else { SqlCommand cmd = new SqlCommand("INSERT INTO echarts_user " + "(username,office,office_phone,staff_description,staff_id,staff_name,status,supervisor) " + "VALUES('" + username + "','" + user.Properties["physicalDeliveryOfficeName"].Value + "','" + user.Properties["telephoneNumber"].Value + "','" + user.Properties["title"].Value + "','" + user.Properties["employeeNumber"].Value + "','" + user.Properties["displayName"].Value + "','" + "Active" + "','" + getManager(user.Properties["manager"].Value.ToString()) + "')", cn); if (cmd.ExecuteNonQuery() == 0) { Response.Write("INSERT FAILED"); } else { HttpCookie staffid = new HttpCookie("staff_id"); staffid.Value = (String)user.Properties["employeeNumber"].Value; staffid.Expires = DateTime.UtcNow.AddMonths(6); staffid.Domain = EchartsAuth.domainName; Response.Cookies.Add(staffid); HttpCookie firstLogin = new HttpCookie("first_login"); firstLogin.Domain = EchartsAuth.domainName; Response.Cookies.Add(firstLogin); doRedirect(Request.QueryString["continue"]); } } } finally { cn.Close(); } }
//Dim LDAP_Path คือ ชื่อ Domain หรือชื่อ Window ที่ต้องการตรวจสอบสิทธิ์----------- public string AuthenticateUser(string LDAP_Path, string user, string pass) { System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry(LDAP_Path, user, pass, AuthenticationTypes.Secure); try { DirectorySearcher ds = new DirectorySearcher(de); ds.FindOne(); return ""; } catch (Exception ex) { return ex.Message; } }
public static string getUsername(string user_id,string domain) { DirectoryEntry de = new DirectoryEntry(@"LDAP://DC="+ domain +",DC=ad,DC=flextronics,DC=com"); DirectorySearcher ds = new DirectorySearcher(de, "SAMAccountName=" + user_id); SearchResult result = ds.FindOne(); if (result == null) return ""; else { string n = result.Path.ToString();// (result.Properties["cn"].Count > 0) ? (string)result.Properties["cn"][0] : user_id; return n; } }
private bool ConexaoOK(string p_Usuario, string p_Senha, string p_Dominio, string p_Porta) { bool Resp = false; try { DirectoryEntry _DirectoryEntry = new DirectoryEntry("LDAP://" + p_Dominio + ":" + p_Porta, p_Usuario, p_Senha); DirectorySearcher _DirectorySearcher = new DirectorySearcher(_DirectoryEntry); _DirectorySearcher.PropertiesToLoad.Add("displayName"); _DirectorySearcher.PropertiesToLoad.Add("SAMAccountName"); _DirectorySearcher.Filter = "(|(displayName=TESTEDECONEXAO) (SAMAccountName=TESTEDECONEXAO))"; SearchResult _SearchResult = _DirectorySearcher.FindOne(); Resp = true; } catch (Exception) { } return(Resp); }
/// <summary> /// Via user account get user info /// </summary> /// <param name="directoryEntry">User DirectoryEntry</param> /// <param name="sAMAccountName">User Account</param> /// <returns>User Info</returns> public static SearchResult GetSearchResultByAccount(DirectoryEntry directoryEntry, string sAMAccountName) { DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry); directorySearcher.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))"; directorySearcher.SearchScope = SearchScope.Subtree; try { SearchResult result = directorySearcher.FindOne(); if (result != null) { return(result); } } catch (Exception ex) { MessageService.ShowMessage(ex.Message); } return(null); }
public static DirectoryEntry GetDirectoryEntryOfouName(string entryPath, string ouName) { if (entryPath == "") { entryPath = ADPath; } DirectoryEntry de = new DirectoryEntry(entryPath);//GetDirectoryObject(); DirectorySearcher deSearch = new DirectorySearcher(de); deSearch.Filter = "(&(objectClass=organizationalUnit)(OU=" + ouName + "))"; deSearch.SearchScope = SearchScope.Subtree; try { SearchResult result = deSearch.FindOne(); return(result.GetDirectoryEntry()); } catch { return(null); } }
public ActionResult GetChia(LoginModel login) { try { if (ModelState.IsValid && login.UserName != " " && login.Password != " ") { var directoryEntry = new DirectoryEntry("LDAP://corpdcberl01.northamerica.cerner.net"); directoryEntry.Username = login.UserName; directoryEntry.Password = login.Password; var directorySearcher = new DirectorySearcher(directoryEntry); SearchResult result = directorySearcher.FindOne(); user = login.UserName; pwd = login.Password; FormsAuthentication.SetAuthCookie(user, false); Session["userName"] = user; ErrorMessage = " "; from = DateTime.Today.AddDays(-180).ToString("yyyy-MM-dd"); to = DateTime.Now.ToString("yyyy-MM-dd"); DeptList = new List <SelectListItem>(); GetDeptList(ref DeptList); ViewBag.DeptList = DeptList; SelectedDept[0] = "General_Laboratory"; ViewBag.SelectedDept = SelectedDept; Getdata = 1; return(Redirect("~/ChiaApplication/GetChiaList")); } else { TempData["ErrorMessage"] = "UserName or Password cannot be Empty!"; return(Redirect("~/ChiaApplication/Login")); } } catch (Exception e) { TempData["ErrorMessage"] = e.Message; return(Redirect("~/ChiaApplication/Login")); } }
public static bool CheckPwd(string username, string password) { DirectoryEntry de = null; DirectorySearcher ds = null; bool flag = false; try { de = new DirectoryEntry(ADPath, username, password, AuthenticationTypes.Secure); ds = new DirectorySearcher(de); SearchResult result = ds.FindOne(); if (result != null) { flag = true; } else { flag = false; } } catch (Exception ex) { flag = false; } finally { if (ds != null) { ds.Dispose(); } if (de != null) { de.Dispose(); } } return(flag); }
/* goodG2B() - use goodsource and badsink */ private void GoodG2B() { string data; while (true) { /* FIX: Use a hardcoded string */ data = "foo"; break; } using (DirectoryEntry de = new DirectoryEntry()) { /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection */ using (DirectorySearcher search = new DirectorySearcher(de)) { search.Filter = "(&(objectClass=user)(employeename=" + data + "))"; search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("telephonenumber"); SearchResult sresult = search.FindOne(); } } }
/// <summary> /// 查找目录项 /// </summary> /// <param name="category">分类 users</param> /// <param name="name">用户名</param> /// <returns>目录项实体</returns> public static DirectoryEntry FindObject(string category, string name) { DirectoryEntry de = null; DirectorySearcher ds = null; DirectoryEntry userEntry = null; try { //de = new DirectoryEntry(ADPath, adminUser, adminPwd, AuthenticationTypes.Secure); de = new DirectoryEntry(ADPath); ds = new DirectorySearcher(de); string queryFilter = string.Format("(&(objectCategory=" + category + ")(sAMAccountName={0}))", name); ds.Filter = queryFilter; ds.Sort.PropertyName = "cn"; SearchResult sr = ds.FindOne(); if (sr != null) { userEntry = sr.GetDirectoryEntry(); } return(userEntry); } catch (Exception ex) { DomainUser._failed = ex.Message.ToString(); return(new DirectoryEntry()); } finally { if (ds != null) { ds.Dispose(); } if (de != null) { de.Dispose(); } } }
public IEnumerable <UserGroup> GetUserGroups(string userName) { IEnumerable <UserGroup> GetUserGroups(string domain) { const string memberOf = "memberOf"; var userGroups = new List <UserGroup>(); //Strip the Domain Name from userName if included string strippedName = StripDomain(userName); //Create a search by User Name using (var search = new DirectorySearcher(new DirectoryEntry(domain), $"(samaccountname={strippedName})")) { //Get the group membership for the user search.PropertiesToLoad.Add(memberOf); var result = search.FindOne(); if (result is SearchResult) { int groupsCount = result.Properties[memberOf].Count; for (int counter = 0; counter < groupsCount; counter++) { string groupName = GetGroup((string)result.Properties[memberOf][counter]); if (groupName is string) { userGroups.Add(new UserGroup { GroupName = groupName }); } } } } return(userGroups); } return(Domains.AsParallel().Select(x => GetUserGroups(x)).SelectMany(y => y)); }
private string GetUserProperty(string userName, string propertyName) { using (DirectoryEntry directoryEntry = this.GetDirectoryEntry()) { using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry)) { directorySearcher.Filter = "(&(objectCategory=person)(samAccountName=" + userName + "))"; directorySearcher.SearchScope = SearchScope.Subtree; SearchResult searchResult = directorySearcher.FindOne(); if (searchResult.Properties[propertyName].Count > 0) { return(this.GetCommonName(searchResult.Properties[propertyName][0].ToString())); } else { return(string.Empty); } } } }
protected void Page_Load(object sender, EventArgs e) { logfilepath = Request.PhysicalApplicationPath + @"\poc_world\tools\ocr\log\ocrlog.csv"; if (!IsPostBack) { /*ユーザー情報取得*/ string sn = ""; //姓 string gn = ""; //名 string tt = ""; //役職 string dm = ""; //所属 string em = ""; //メールアドレス string pg = "Azure"; var directoryEntry = new DirectoryEntry(); var directorySearcher = new DirectorySearcher(directoryEntry); string un = User.Identity.Name; un = un.Substring(un.LastIndexOf(@"\") + 1, un.Length - (un.LastIndexOf(@"\") + 1)); directorySearcher.Filter = String.Format("(&(objectClass=user)(samAccountName={0}))", un); var result = directorySearcher.FindOne(); if (result != null) { var entry = result.GetDirectoryEntry(); sn = (string)entry.Properties["sn"].Value; gn = (string)entry.Properties["givenName"].Value; tt = (string)entry.Properties["title"].Value; if (tt == null) { tt = "-"; } dm = (string)entry.Properties["department"].Value; em = (string)entry.Properties["mail"].Value; } /*ログに作成記録 */ Application.Lock(); using (StreamWriter sw = new StreamWriter(logfilepath, true, System.Text.Encoding.GetEncoding("shift_jis"))) { sw.WriteLine(DateTime.Now.ToString("yyyy/MM/dd,HH:mm:ss") + "," + Request.UserHostName + "," + User.Identity.Name + "," + sn + " " + gn + "," + tt + "," + dm + "," + em + "," + pg); } Application.UnLock(); } }
private static DirectoryEntry GetDirectoryEntryOfGroup(string entryPath, string groupName) { if (entryPath == "") { entryPath = ADPath; } DirectoryEntry de = new DirectoryEntry(entryPath);//GetDirectoryObject(); DirectorySearcher deSearch = new DirectorySearcher(de); deSearch.Filter = "(&(objectClass=group)(CN=" + groupName + "))"; deSearch.SearchScope = SearchScope.Subtree; try { SearchResult result = deSearch.FindOne(); return(result.GetDirectoryEntry()); } catch { return(null); } }
/// <summary> /// 获得指定路径的节点的对象 /// </summary> /// <param name="condition"></param> /// <param name="LDAPDomain">制定路径</param> /// <returns>DirectoryEntry</returns> public DirectoryEntry CommonWayEntry(string condition, string LDAPDomain) { DirectoryEntry de = Iadc.GetDirectoryObject(LDAPDomain); //获得指定路径下的节点的路径 DirectorySearcher deSearch = new DirectorySearcher(); deSearch.SearchRoot = de; deSearch.Filter = condition; deSearch.SearchScope = SearchScope.Subtree; SearchResult results = deSearch.FindOne(); if (results != null) { de = new DirectoryEntry(results.Path, ADUser, ADPassword, AuthenticationTypes.Secure); return(de); } else { return(null); } }
public bool ChangeUserPassword(string login, string newPassword) { var adConfig = CustomConfiguration.Settings.ActiveDirectoryData(); var connectionString = ConfigurationManager.ConnectionStrings[adConfig.ConnectionStringName].ConnectionString; var directoryEntry = new DirectoryEntry(connectionString, adConfig.UserName, adConfig.Password); var searcher = new DirectorySearcher(directoryEntry, $"sAMAccountName={login}") { SearchScope = SearchScope.Subtree }; var adUser = searcher.FindOne(); if (adUser == null) { return(false); } var userPath = adUser.Properties["adspath"][0].ToString(); directoryEntry = new DirectoryEntry(userPath, adConfig.UserName, adConfig.Password); try { directoryEntry.Invoke("SetPassword", new object[] { newPassword }); directoryEntry.Properties["LockOutTime"].Value = 0; } catch (TargetInvocationException erro) { if (erro.InnerException != null) { throw erro.InnerException; } throw; } directoryEntry.Close(); return(true); }
private static string ConnectionDescriptor(string directoryServer, string defaultAdminContext, string serviceName) { string ldapAdress = $"LDAP://{directoryServer}/{defaultAdminContext}"; string query = $"(&(objectclass=orclNetService)(cn={serviceName}))"; string orclnetdescstring = "orclnetdescstring"; DirectoryEntry directoryEntry = new DirectoryEntry(ldapAdress, null, null, AuthenticationTypes.Anonymous); DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, query, new[] { orclnetdescstring }, SearchScope.Subtree); SearchResult searchResult = directorySearcher.FindOne(); byte[] value = searchResult.Properties[orclnetdescstring][0] as byte[]; if (value != null) { string descriptor = Encoding.Default.GetString(value); return(descriptor); } throw new Exception("Error qerying ldap"); }
internal string GetNetbiosDomainNameIfAvailable(string dnsDomainName) { DirectoryEntry searchRoot = new DirectoryEntry(this.GetADsPath("CN=Partitions," + ((string)System.Web.Security.PropertyManager.GetPropertyValue(this.rootdse, "configurationNamingContext"))), this.GetUsername(), this.GetPassword()); DirectorySearcher searcher = new DirectorySearcher(searchRoot) { SearchScope = System.DirectoryServices.SearchScope.OneLevel }; StringBuilder builder = new StringBuilder(15); builder.Append("(&(objectCategory=crossRef)(dnsRoot="); builder.Append(dnsDomainName); builder.Append(")(systemFlags:1.2.840.113556.1.4.804:=1)(systemFlags:1.2.840.113556.1.4.804:=2))"); searcher.Filter = builder.ToString(); searcher.PropertiesToLoad.Add("nETBIOSName"); SearchResult res = searcher.FindOne(); if ((res == null) || !res.Properties.Contains("nETBIOSName")) { return(dnsDomainName); } return((string)System.Web.Security.PropertyManager.GetSearchResultPropertyValue(res, "nETBIOSName")); }
public ADUser FindNameByQID(string QID) { ADUser aDUser = new ADUser(); try { DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain + "/" + defaultRootOU, userName, password); DirectorySearcher search = new DirectorySearcher(entry); // search.Filter = "(&(objectCategory=person)(sAMAccountName=*)(mail=" + emailAddress + "))"; search.Filter = string.Format("(employeeID={0})", QID); string[] properties = new string[] { "SAMAccountName" }; //foreach (String property in properties) // search.PropertiesToLoad.Add(property); //search.Filter = "(sAMAccountName=Uname)"; SearchResult result = search.FindOne(); StringBuilder str = new StringBuilder(); ResultPropertyCollection prop = result.Properties; var coll = prop.PropertyNames; if (result != null) { aDUser = new ADUser { QID = (string)result.Properties["EmployeeId"][0], //oUserPrincipal?.EmployeeId, Email = (string)result.Properties["mail"][0], // oUserPrincipal?., UserName = (string)result.Properties["SAMAccountName"][0], NameAr = (string)result.Properties["DisplayName"][0], //oUserPrincipal?.DisplayName, NameEN = (string)result.Properties["GivenName"][0], // oUserPrincipal?.GivenName, //Groups = (string)result.Properties["EmailAddress"][0]// oUserPrincipal?.GetAuthorizationGroups().Select(g => g.Name).ToList() }; } } catch (Exception ex) { // throw; } return(aDUser); }
private void AddResourceToDataTable(string userPath) { try { DataRow dr = _adUsers.NewRow(); SearchResult searchResult; using (var directoryEntry = new DirectoryEntry(userPath)) { using (var searcher = new DirectorySearcher(directoryEntry, "(objectClass=user)")) { searchResult = searcher.FindOne(); } } string spFieldName = string.Empty; string adFieldName = string.Empty; foreach (string field in _adFieldMappings) { try { spFieldName = _adFieldMappingValues[field].ToString(); //For testing only...remove adFieldName = field; //For testing only...remove dr[spFieldName] = searchResult.Properties[field][0].ToString(); } catch (Exception ex) { _ExecutionLogs.Add(" INFO -- Location: AddResourceToDataTable() SPField:" + spFieldName + " ADField:" + adFieldName + " -- Message: " + adFieldName + " property not set for " + userPath + "."); } } dr["SID"] = GetUserSID(userPath); _adUsers.Rows.Add(dr); } catch (Exception ex) { _ExecutionLogs.Add(" ERROR -- Location: AddResourceToDataTable() module level -- Message: " + ex.Message); _hasErrors = true; } }
public bool FindOneUser(String user) { if (USRDU.ContainsKey(user)) { return(true); } DirectorySearcher USER_SEARCH = getUserSearcher(); //string filter_save = USER_SEARCH.Filter; foreach (Domain d in Forest.GetCurrentForest().Domains) { USER_SEARCH.SearchRoot = d.GetDirectoryEntry(); USER_SEARCH.Filter = "(&(ObjectClass=user)(!ObjectClass=computer)(employeeID=*)(sAMAccountName=" + user + "))"; SearchResult r = USER_SEARCH.FindOne(); if (r != null) { AddUser(r); return(true); } } //USER_SEARCH.Filter = filter_save; return(false); }
protected void Page_Load(object sender, EventArgs e) { DirectorySearcher adsSearch = Helpers.DirectorySearcher(); adsSearch.PropertiesToLoad.Add("sAMAccountName"); //adsSearch.Filter = "sAMAccountName=" + Page.User.Identity.Name.Substring(4); adsSearch.Filter = "sAMAccountName=aleksandar.vojvodic" /* + Page.User.Identity.Name.Substring(4)*/; SearchResult oResult = adsSearch.FindOne(); if (Helpers.GetPropertyString(oResult, "cn") != "") { ImageButton1.PostBackUrl = "PhoneBook.aspx?account=" + Helpers.GetPropertyString(oResult, "cn"); } if (Helpers.GetPropertyString(oResult, "department") != "") { ImageButton3.PostBackUrl = "Team.aspx?team=" + Server.UrlEncode(Helpers.GetPropertyString(oResult, "department")); } if (Helpers.GetPropertyString(oResult, "physicalDeliveryOfficeName") != "") { ImageButton4.PostBackUrl = "Office.aspx?office=" + Helpers.GetPropertyString(oResult, "physicalDeliveryOfficeName"); } }
public UserBasicInfo GetDomainUser(string adAccount, string validatePwd, out string errorMessage) { DirectoryEntry entry = new DirectoryEntry(LDAPPath, adAccount, validatePwd); try { Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + adAccount + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (result != null) { DirectoryEntry de = result.GetDirectoryEntry(); UserBasicInfo ui = new UserBasicInfo(); ui.AdName = adAccount; if (de.Properties["GivenName"].Value != null) { ui.NickName = de.Properties["GivenName"].Value.ToString(); } if (de.Properties["sn"].Value != null) { ui.NickName += " " + de.Properties["sn"].Value.ToString(); } if (de.Properties["mail"].Value != null) { ui.Email = de.Properties["mail"].Value.ToString(); } errorMessage = null; return(ui); } } catch (Exception ex) { errorMessage = ex.Message; return(null); } errorMessage = null; return(null); }
public ScanUser(string userName, Settings settings) { _settings = settings; UserName = userName; var lDAPSearchURL = $"LDAP://{_settings.UsersDN}"; var filterString = $"(&(objectCategory=person)(objectClass=user)({_settings.FolderNameMapAttr}={UserName}))"; try { using (DirectoryEntry domain = new DirectoryEntry(lDAPSearchURL)) { using (DirectorySearcher searcher = new DirectorySearcher(domain, filterString)) { HomeDirectory = searcher.FindOne().Properties[_settings.UsersHomeDirAttr][0].ToString(); } } } catch (Exception) { } //HomeDirectory = "E:\\CodingTestField\\IvanovII"; }
public ADAttributes Load(string cn) { bool inHierarchy = false; String rootOU = AppConfiguration.RootOU; if (cn.ToLower().Contains(rootOU.ToLower())) { log.Debug("cn=" + cn + " is considered in the hierarchy of root=" + rootOU); inHierarchy = true; } // if the CN is not a child of any of the roots (or one of the roots), we block it) if (!inHierarchy) { return(Blocked(cn)); } using (DirectoryEntry searchRoot = new DirectoryEntry()) { using (DirectorySearcher deSearch = new DirectorySearcher(searchRoot)) { deSearch.Filter = "(&(distinguishedName=" + cn + "))"; deSearch.SearchScope = SearchScope.Subtree; SearchResult result = deSearch.FindOne(); // if we cannot find it in AD, log it and return a blocked entry if (result == null) { log.Warn("Unable to find object in Active Directory: " + cn); return(Blocked(cn)); } bool isUser = IsUser(result); return(AttributesBuilder.BuildAttributes(result.Properties)); } } }
private bool AuthenticateUser(string domainName, string userName, string password) { bool ret = false; try { DirectoryEntry de = new DirectoryEntry("LDAP://" + domainName, userName, password); DirectorySearcher dsearch = new DirectorySearcher(de); SearchResult results = null; results = dsearch.FindOne(); ret = true; } catch { ret = false; } return(ret); }
//internal static Collection GetGroupUsers(string strGroupName) //{ // string usr = FTPUser.GetMasterUser(); /// persalnumber; // string pwd = FTPUser.GetMasterPwd(); // string get_ldap_string = FTPUser.GetAppOUContext(); // string ldapstring = "LDAP://" + FTPUser.GetIPaddressString() + "/CN=FTP_ACCESS," + get_ldap_string; // DirectoryEntry de = new DirectoryEntry(ldapstring, usernme, pwd); // DirectorySearcher ds = new DirectorySearcher(de); // Collection sbGroupUsers = null; // { // ds.PropertiesToLoad.Add("memberOf"); // try // { // SearchResultCollection dsResultColl = ds.FindAll(); // short shtCounter = 0; // if (dsResultColl == null) // { return null; } // //ResultPropertyCollection myResultPropColl; // //strUsers = dsResultColl.Properties["memberOf"].IndexOf(shtCounter).ToString(); // //sbGroupUsers.Add(strUsers.ToString().Trim()); // //sbGroupUsers.Add(ControlChars.CrLf); // foreach (string myKey in myResultPropColl.PropertyNames) // { // string tab = " "; // Console.WriteLine(myKey + " = "); // foreach (Object myCollection in myResultPropColl[myKey]) // { // Console.WriteLine(tab + myCollection); // } // } // ds.Dispose(); // de.Dispose(); // } // catch (Exception ex) // { // Interaction.MsgBox("Error in GetGroupUsers Function" + Constants.vbNewLine + ex.Message.ToString(), MsgBoxStyle.Information, "Active Directory Error"); // } // } // return sbGroupUsers; //} public static StringCollection GetFTPUsers3() { string usr = FTPUser.GetMasterUser(); /// persalnumber; string pwd = FTPUser.GetMasterPwd(); string get_ldap_string = FTPUser.GetAppOUContext(); StringCollection col = new StringCollection(); string ldapstring = "LDAP://" + FTPUser.GetIPaddressString() + "/CN=FTP_ACCESS," + get_ldap_string; try { DirectoryEntry de = new DirectoryEntry(ldapstring, usr, pwd); DirectorySearcher ds = new DirectorySearcher(de); SearchResult sr = ds.FindOne(); if (sr != null) { DirectoryEntry myde = sr.GetDirectoryEntry(); string mySearchResultPath = sr.Path; ResultPropertyCollection myResultPropColl; myResultPropColl = sr.Properties; foreach (string user in myde.Properties) { Interaction.MsgBox(user.ToString(), MsgBoxStyle.OkOnly, "System Message"); } de.Dispose(); myde.Dispose(); } else { //Console.WriteLine("The '" + myLDAPPath + "' path not found."); } } catch (Exception ex) { Interaction.MsgBox(ex.Message); } return(col); }
public static bool IsValidDomainName(string domainName) { bool ck = true; try { DirectoryEntry entry = new DirectoryEntry(); entry.Path = GetDomain(domainName); DirectorySearcher _DirectorySearcher = new DirectorySearcher(entry); _DirectorySearcher.Filter = "(SAMAccountName=*)"; _DirectorySearcher.SearchScope = SearchScope.Subtree; _DirectorySearcher.FindOne(); } catch (Exception ex) { ck = false; } return(ck); }
static void testQuery(int counter) { try { using (var de = new DirectoryEntry(ldapurl, login, kode, AuthenticationTypes.Secure)) using (var deSearch = new DirectorySearcher(de, string.Format("(&(objectClass=user) (cn={0}))", login))) { deSearch.FindOne(); //hvis man er nået hertil uden exception er login gået godt. Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Ok. ({0})", counter); Console.ResetColor(); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); Console.ResetColor(); } }
public bool FindOneDomainUser(String domainuser) { DirectorySearcher USER_SEARCH = getUserSearcher(); string domain = domainuser.Split('\\')[0].ToUpper(); string user = domainuser.Split('\\')[1].ToUpper(); if (USRDU.ContainsKey(user)) { return(true); } bool found = false; foreach (Domain d in Forest.GetCurrentForest().Domains) { if (d.GetDirectoryEntry().Properties["name"].Value.ToString().ToUpper().Equals(domain)) { USER_SEARCH.SearchRoot = d.GetDirectoryEntry(); found = true; break; } } if (!found) { return(false); } //string filter_save = USER_SEARCH.Filter; USER_SEARCH.Filter = "(&(ObjectClass=user)(!ObjectClass=computer)(employeeID=*)(sAMAccountName=" + user + "))"; SearchResult r = USER_SEARCH.FindOne(); //USER_SEARCH.Filter = filter_save; if (r == null) { return(false); } AddUser(r); return(true); }
// check of existence of the user in AD public static bool Exists(string username) { bool found = false; DirectoryEntry myconnection = createDirectoryEntry(); string SearchFilter = string.Format("(&((&(objectCategory=Person)(objectClass=User)))(userPrincipalName={0}", username); DirectorySearcher searchname = new DirectorySearcher(myconnection, SearchFilter) { SearchScope = SearchScope.Subtree, PropertyNamesOnly = true }; // get result values SearchResult mysearchnameresult = searchname.FindOne(); if (mysearchnameresult.Properties.Values.Equals(username)) { found = true; } searchname.Dispose(); return(found); }
/// <summary> /// Attempts to get user details from Active directory based on the user's Active Directory login username /// </summary> /// <param name="loginUserName">the Active Directory username for the user.</param> /// <returns>a DirectoryEntry object containing the user details, null if we could not get the details</returns> public SearchResult GetUserDirectoryEntryDetails(string loginUserName) { try { var de = new DirectoryEntry(LDapConnectionString, "username", "passworrd") { AuthenticationType = AuthenticationTypes.Secure }; var deSearch = new DirectorySearcher { SearchRoot = de, Filter = "(&(objectClass=user)(SAMAccountName=" + loginUserName + "))", SearchScope = SearchScope.Subtree }; //SearchResultCollection results; //Search the USER object in the hierachy //Add the attributes which we want to return to the search result var results = deSearch.FindOne(); return(results); } catch (Exception ex) { //Console.WriteLine("ERROR: " + ex.Message ); //ApplicationContext.CurrentHTTPResponse.Write(ex.Message + "<br /><br />"); while (ex.InnerException != null) { _errorMessage += ex.InnerException.Message; //ApplicationContext.CurrentHTTPResponse.Write( ex.InnerException.Message.ToString() + "<br /><br />"); } //end while //return (errorMessage); return(null); } //end try/catch } //end GetUserDirectoryEntryDetails.
/// <summary> /// This is used mainy for the logon process to ensure that the username and password match /// </summary> /// <param name="UserName"></param> /// <param name="Password"></param> /// <returns></returns> public static DirectoryEntry UserExists(string UserName, string Password) { //create an instance of the DirectoryEntry DirectoryEntry de = GetDirectoryObject(); //UserName,Password); //create instance fo the direcory searcher var deSearch = new DirectorySearcher(); //set the search filter deSearch.SearchRoot = de; deSearch.Filter = "((objectClass=user)(cn=" + UserName + ")(userPassword="******"))"; deSearch.SearchScope = SearchScope.Subtree; //set the property to return //deSearch.PropertiesToLoad.Add("givenName"); //find the first instance SearchResult results = deSearch.FindOne(); //if the username and password do match, then this implies a valid login //if so then return the DirectoryEntry object de = new DirectoryEntry(results.Path, ADUser, ADPassword, AuthenticationTypes.Secure); return(de); }
// code by lalit Joshi private bool Authenticate(string userName, string password, string domain) { bool authentic = false; try { DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password); DirectorySearcher srchr = new DirectorySearcher(entry); srchr.Filter = string.Format("(SAMAccountName={0})", userName); //srchr.Filter = string.Format("SAMAccountName=0", userName); SearchResult res = srchr.FindOne(); if (res != null) authentic = true; } catch (DirectoryServicesCOMException) { } return authentic; }
private bool __defineUser(ref DirectorySearcher search) { //load properites for user; search.PropertiesToLoad.Add("cn"); search.PropertiesToLoad.Add("telephoneNumber"); search.PropertiesToLoad.Add("facsimileTelephoneNumber"); search.PropertiesToLoad.Add("mobile"); search.PropertiesToLoad.Add("ipphone"); search.PropertiesToLoad.Add("memberof"); search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("department"); search.PropertiesToLoad.Add("title"); search.PropertiesToLoad.Add("sAMAccountName"); //search.PropertiesToLoad.Add("dc"); SearchResult result = search.FindOne(); if (result == null) return false; _path = result.Path; _uid = result.Properties["sAMAccountName"][0].ToString(); _name = (result.Properties["cn"].Count > 0) ? (string)result.Properties["cn"][0] : _uid; _department = setProperity(ref result,"department");// (result.Properties["department"].Count > 0) ? (string)result.Properties["department"][0] : ""; tel = setProperity(ref result, "telephoneNumber"); title = setProperity(ref result, "title"); email = setProperity(ref result, "mail"); fax = setProperity(ref result, "facsimileTelephoneNumber"); mobile = setProperity(ref result, "mobile"); ipPhone = setProperity(ref result, "ipphone"); //_domain = setProperity(ref result, "DC"); __setGroup(ref result); return true; }
private void getInfo(ref string date, ref string ddstartTime, ref string ddendTime, ref string room, ref string body, ref string sVal) { string DOMAIN_NAME = "ITSERVICES"; DirectoryEntry dirEntry = new DirectoryEntry( "LDAP://" + DOMAIN_NAME ); DirectorySearcher dirSearcher = new DirectorySearcher( dirEntry ); dirSearcher.Filter = "(mail=" + email.Text + "@calrecycle.ca.gov)"; SearchResult result = dirSearcher.FindOne(); DirectoryEntry person = result.GetDirectoryEntry(); string managerName = "", department = ""; string name = person.Properties["givenName"].Value.ToString() + " " + person.Properties["sn"].Value.ToString(); string location = person.Properties["physicalDeliveryOfficeName"].Value.ToString(); string phone = person.Properties["telephoneNumber"].Value.ToString(); try { department = person.Properties["department"].Value.ToString(); } catch { } try { string manager = person.Properties["manager"].Value.ToString(); string firstManagerName = manager.Substring( manager.IndexOf( "," ) + 2, manager.IndexOf( ",", manager.IndexOf( "," ) ) - 4 ); string lastManagerName = manager.Substring( 3, manager.IndexOf( "," ) - 4 ); managerName = firstManagerName + " " + lastManagerName; } catch { managerName = "Not Found"; } userEmail = email.Text + "@calrecycle.ca.gov"; date = calBtn.Text; ddstartTime = startTime.Text; ddendTime = endTime.Text; if (!epaConf.SelectedValue.Equals("")) { room = epaConf.Text; } else if (!kTraining.SelectedValue.Equals("")) { room = kTraining.Text; sVal = "801k"; } else if (!epaTraining.SelectedValue.Equals("")) { room = epaTraining.Text; } else if (!epaRooms.SelectedValue.Equals("")) { room = epaRooms.Text; } else if (!kRooms.SelectedValue.Equals("")) { room = kRooms.Text; sVal = "801k"; } string link = @"http://epanet.ca.gov/Rooms/RoomDetail.asp?REFERER2=MyMtg.asp&ROOMID=" + getRoomID( room ) + @"&DATE=" + DateTime.Now.ToString( "M/d/yyyy" ); StringBuilder equipmentSelect = new StringBuilder(); if ( equipment.Items[0].Selected ) equipmentSelect.Append( " • Laptop</br>" ); if ( equipment.Items[1].Selected ) equipmentSelect.Append( " • Projector Screen</br>" ); if ( equipment.Items[2].Selected ) equipmentSelect.Append( " • Projector</br>" ); if ( equipment.Items[3].Selected ) equipmentSelect.Append( " • Speakers</br>" ); if ( equipment.Items[4].Selected ) equipmentSelect.Append( " • Conference Phone</br>" ); if ( equipment.Items[5].Selected ) equipmentSelect.Append( " • Other (see comments)</br>" ); if ( networkReq.Items[0].Selected ) { equipmentSelect.Append( " • CalRecycle Network Access Required</br>" ); } else { equipmentSelect.Append( " • Wifi Access Required" ); } body = "<b><u>Requestor Information</u></b></br>" + "Name: " + name + ", " + department + "</br>" + "Email: " + userEmail + "</br>" + "Phone: " + phone + "</br>" + "Location: " + location + "</br>" + "Ticket Number: " + ticket.Text + "</br>" + "<a href=" + link + ">Room Reservation</a></br></br>" + "<b><u>Equipment Information</u></b></br>" + equipmentSelect.ToString() + "</br></br>" + "<b><u>Comments</u></b></br>" + commentBox.Text.Replace( System.Environment.NewLine, "</br>" ); // if (!kTraining.SelectedValue.Equals("") || !kRooms.SelectedValue.Equals("") ) // sVal = "801k"; }
public bool CheckUserAuthentication(String userAccount) { //DirectoryEntry entry = new DirectoryEntry(LDAPConnString); DirectoryEntry entry = new DirectoryEntry(lDAPConnString, userName, password); //Change the domain name to match the target domain String account = userAccount; //string group = "AdminGroup"; try { //Search Actived Directory for the username used during login and generate list of groups the user is a member of DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + account + ")"; search.PropertiesToLoad.Add("memberOf"); SearchResult result = search.FindOne(); //Search Active Directory for the group specified in the authorizedGroup variable and list the group's members. DirectorySearcher groupSearch = new DirectorySearcher(entry); groupSearch.Filter = "(SAMAccountName=" + authorizedGroup + ")"; groupSearch.PropertiesToLoad.Add("member"); SearchResult groupResult = groupSearch.FindOne(); //Compare groups the user is a member of with the specified group. If a match, return true to the calling aspx page. if (result != null) { int allGroupCount = result.Properties["memberOf"].Count; int checkGroupCount = groupResult.Properties["member"].Count; for (int i = 0; i < allGroupCount; i++) { string number = lDAPContextString + result.Properties["memberOf"][i].ToString(); for (int j = 0; j < checkGroupCount; j++) { string grp = groupResult.Path[j].ToString(); string usr = result.Path.ToString(); if (number == groupResult.Path.ToString()) { return true; } } } } else { return false; } } catch (Exception ex) { string debug = ex.Message; return false; } return false; }
/*private static string getOsName() { var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>() select x.GetPropertyValue("Caption")).FirstOrDefault(); return name != null ? name.ToString() : "Unknown"; }*/ protected void Page_Load(object sender, EventArgs e) { //Lokaalin käyttäjän käyttäjänimi. string userAccountName = User.Identity.Name.ToString().Substring(8); //Lokaalin tietokoneen nimi string[] computer_name = System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName.Split(new Char[] { '.' }); String ecn = System.Environment.MachineName; _computerName = computer_name[0].ToString(); //Hakee AD:sta tarvittavat tiedot käyttäjälle using (DirectoryEntry de = new DirectoryEntry("LDAP://adturku.fi")) { using (DirectorySearcher adSearch = new DirectorySearcher(de)) { adSearch.PropertiesToLoad.Add("cn"); // Kokonimi adSearch.PropertiesToLoad.Add("mail"); // Sähköposti adSearch.PropertiesToLoad.Add("telephoneNumber"); // Puhelinnumero adSearch.PropertiesToLoad.Add("Company"); // Toimiala adSearch.PropertiesToLoad.Add("Department"); // Yksikkö adSearch.PropertiesToLoad.Add("streetaddress"); // Toimipiste //adSearch.PropertiesToLoad.Add("City"); // kaupunki adSearch.Filter = "(sAMAccountName="+ userAccountName+")"; //haku käyttäjänimellä SearchResult adSearchResult = adSearch.FindOne(); var searchPropCollection = adSearchResult.Properties; string[] info = new string[15]; int infoRivi = 0; //Noutaa AD-haun tulokset ja sijoittaa ne tietyille paikoilleen tulostaulukkoon (_userInfoAD). Skippaa adspathin, jota ei tässä tarvita. foreach (string tulos in searchPropCollection.PropertyNames) { if (tulos.Equals("cn")) { infoRivi = 0; } if (tulos.Equals("mail")) { infoRivi = 1; } if (tulos.Equals("telephonenumber")) { infoRivi = 2; } if (tulos.Equals("company")) { infoRivi = 3; } if (tulos.Equals("department")) { infoRivi = 4; } if (tulos.Equals("streetaddress")) { infoRivi = 5; } if (tulos.Equals("adspath")) { continue; } foreach (Object myCollection in searchPropCollection[tulos]) { info[infoRivi] = myCollection.ToString(); } } _userInfoAD = info; } } //Asetetaan käyttäjän sähköposti täältä koodin puolelta paikalleen, koska emailin lähetyksessä käytetään //asp net tekstikenttää, joka saattaa saada uuden arvon lomaketta täytettäessä sähköposti.Text = userEmail; //Muuttaan dropdown-listan testiosoite käyttäjän omaksi emailiksi testiosoite.Value = userEmail; }
//-------------------------------------------------------------------- /// <summary> /// If user is active directory try to authenticate user from active directory. /// </summary> /// <param name="OUser"></param> //-------------------------------------------------------------------- protected bool IsActiveDirectory(OUser user) { DirectoryEntry entry = null; if (user.ActiveDirectoryDomain != null && user.ActiveDirectoryDomain != string.Empty) { entry = new DirectoryEntry(OApplicationSetting.Current.ActiveDirectoryPath, user.ActiveDirectoryDomain + "\\" + login.UserName, login.Password); } else { entry = new DirectoryEntry(OApplicationSetting.Current.ActiveDirectoryPath, OApplicationSetting.Current.ActiveDirectoryDomain + "\\" + login.UserName, login.Password); } Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + login.UserName + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) return false; return true; }
// Summary: // Gets a List<string> of distinguished names of members belonging to this GroupPrincipalFull // // Returns: // The List<string> of distinguished names of members belonging to this GroupPrincipalFull // // Exceptions: // System.InvalidOperationException: // The underlying store does not support this property. public List<string> GetMemberDNs(bool recursive, bool searchOtherDomains, uint rangeStep) { var de = new DirectoryEntry(string.Format("LDAP://{0}", DistinguishedName)); var searcher = new DirectorySearcher(de) { SearchRoot = de, Filter = "(objectClass=*)" }; var members = new List<string>(); //uint rangeStep = 1000; uint rangeLow = 0; var rangeHigh = rangeLow + (rangeStep - 1); var lastQuery = false; var quitLoop = false; uint count = 0; do { string attributeWithRange; attributeWithRange = !lastQuery ? String.Format("member;range={0}-{1}", rangeLow, rangeHigh) : String.Format("member;range={0}-*", rangeLow); searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add(attributeWithRange); var results = searcher.FindOne(); if (results.Properties.Contains(attributeWithRange)) { foreach (var obj in results.Properties[attributeWithRange]) { count++; var s = obj as string; if (s != null) { members.Add(s); } else if (obj is int) { } } if (lastQuery) { quitLoop = true; } } else { lastQuery = true; } if (lastQuery) { continue; } rangeLow = rangeHigh + 1; rangeHigh = rangeLow + (rangeStep - 1); } while (!quitLoop); var membersToAdd = new List<string>(); foreach (var obj in members) { if (!(obj.ToLowerInvariant().Contains(RootContainer.ToLowerInvariant())) && !searchOtherDomains) { continue; } if (!recursive) { continue; } var gpf = FindByIdentity(new PrincipalContext(ContextType.Domain), IdentityType.DistinguishedName, obj); try { if (!string.IsNullOrEmpty(gpf.DistinguishedName)) { membersToAdd.AddRange(gpf.GetMemberDNs(recursive, searchOtherDomains, rangeStep)); } } catch { continue; } } members.AddRange(membersToAdd); return members; }
public bool HasAccess(string _username) { //If the user should be given access to the system bool Access = false; // If the user has any group memberships or OUs that grant access bool GrantAccess = false; // If the user has any group memberships or OUs that deny access bool DenyAccess = false; // Create an Active Directory searcher then, if possible, locate the user and obtain their // OU and group memberships. // Bind to the users container. // Variables set in class declaration DirectoryEntry entry = new DirectoryEntry(ActiveDirectoryRoot, ActiveDirectorySearcherUserName, ActiveDirectorySearcherPassword, AuthenticationTypes.Secure); // Create a DirectorySearcher object DirectorySearcher mySearcher = new DirectorySearcher(entry); // Create search filter // Variable set when function is called mySearcher.Filter = "(&(objectClass=person)(sAMAccountName=" + _username + "))"; // Get the username from active directory mySearcher.PropertiesToLoad.Add("memberOf"); // Create a SearchResultCollection object to hold a collection of // SearchResults of SearchResults returned by the FindOne method. SearchResult result = mySearcher.FindOne(); int intTotalNumberofGrantAccessGroups = ActiveDirectoryGroupsGrantAccess.Count(); int intTotalNumberofGrantAccessGroupsSetTrue = 0; // Loop through all the group memberships foreach (object value in result.Properties["memberof"]) { // Check to see if they are a member of a group that grants access if (ActiveDirectoryGroupsGrantAccess.Contains((string)value)) { GrantAccess = true; intTotalNumberofGrantAccessGroupsSetTrue++; } else if (ActiveDirectoryGroupsDenyAccess.Contains((string)value)) { DenyAccess = true; } } if (GrantAccess && intTotalNumberofGrantAccessGroups == intTotalNumberofGrantAccessGroupsSetTrue && !(DenyAccess)) { Access = true; } return Access; }
protected void LoginButtonClick(object sender, EventArgs e) { Int32 intUserType = 0; using (DirectoryEntry entry = new DirectoryEntry()) { entry.Username = txt_username.Text; entry.Password = txt_password.Text; DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = "(objectclass=user)"; try { searcher.FindOne(); } catch (DirectoryServicesCOMException ex) { if (ex.ErrorCode == -2147023570) // Login or password is incorrect { lbl_error_message.Text = "Username or password was invalid.<br />"; } return; } } // Open DB connection SqlConnection TM_DB = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SEI_TMConnString"].ConnectionString); TM_DB.Open(); SqlCommand command_GetUser = new SqlCommand("tm_GetUser", TM_DB); command_GetUser.CommandType = CommandType.StoredProcedure; command_GetUser.Parameters.AddWithValue("@UserID", txt_username.Text); SqlDataReader user_reader = command_GetUser.ExecuteReader(); //Get the first user returned if (user_reader.HasRows) { while (user_reader.Read()) { intUserType = (Int32)user_reader["TypeID"]; break; } } else { lbl_error_message.Text = "You are not a current user. Please contact the administrator of Time Machine.<br />"; } user_reader.Close(); user_reader.Dispose(); command_GetUser.Dispose(); // Close DB connection TM_DB.Close(); TM_DB.Dispose(); if (lbl_error_message.Text == tm_EmptyString) { Session["s_user"] = txt_username.Text; if (intUserType >= 1) Response.Redirect("Statistics.aspx"); else Response.Redirect("Timelog.aspx"); } }
/// <summary> /// Finds if the group is "small", meaning that it has less than MaxValRange values (usually 1500) /// The property list for the searcher of a a group has "member" attribute. if there are more results than MaxValRange, there will also be a "member;range=..." attribute /// we can cache the result and don't fear from changes through Add/Remove/Save because the completed/pending lists are looked up before the actual values are /// </summary> internal bool IsSmallGroup() { if (_isSmallGroup.HasValue) { return _isSmallGroup.Value; } _isSmallGroup = false; DirectoryEntry de = (DirectoryEntry)this.UnderlyingObject; Debug.Assert(de != null); if (de != null) { using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base)) { SearchResult sr = ds.FindOne(); if (sr != null) { bool rangePropertyFound = false; foreach (string propName in sr.Properties.PropertyNames) { if (propName.StartsWith("member;range=", StringComparison.OrdinalIgnoreCase)) { rangePropertyFound = true; break; } } // we only consider the group "small" if there is a "member" property but no "member;range..." property if (!rangePropertyFound) { _isSmallGroup = true; SmallGroupMemberSearchResult = sr; } } } } return _isSmallGroup.Value; }
internal static void ResetMachineAccountPassword(string domain, string localMachineName, string server, PSCredential credential, PSCmdlet cmdlet) { // Get domain directory entry and reset the password on the machine account of the local machine string newPassword = null; string domainOrServerName = server ?? domain; try { string dUserName = credential != null ? credential.UserName : null; string dPassword = credential != null ? Utils.GetStringFromSecureString(credential.Password) : null; using (var domainEntry = new DirectoryEntry( "LDAP://" + domainOrServerName, dUserName, dPassword, AuthenticationTypes.Secure)) { using (var searcher = new DirectorySearcher(domainEntry)) { searcher.Filter = "(&(objectClass=computer)(|(cn=" + localMachineName + ")(dn=" + localMachineName + ")))"; SearchResult result = searcher.FindOne(); if (result == null) { string format = server != null ? ComputerResources.CannotFindMachineAccountFromServer : ComputerResources.CannotFindMachineAccountFromDomain; string errMsg = StringUtil.Format(format, domainOrServerName); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "CannotFindMachineAccount", ErrorCategory.OperationStopped, localMachineName); cmdlet.ThrowTerminatingError(error); } else { // Generate a random password of length 120, and reset the password on the machine account using (var targetEntry = result.GetDirectoryEntry()) { newPassword = ComputerWMIHelper.GetRandomPassword(PasswordLength); targetEntry.Invoke("SetPassword", new object[] { newPassword }); targetEntry.Properties["LockOutTime"].Value = 0; } } } } } catch (DirectoryServicesCOMException ex) { string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName); cmdlet.ThrowTerminatingError(error); } catch (TargetInvocationException ex) { string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.InnerException.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName); cmdlet.ThrowTerminatingError(error); } catch (COMException ex) { string errMsg = StringUtil.Format(ComputerResources.FailToResetPasswordOnDomain, ex.Message); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToResetPasswordOnDomain", ErrorCategory.OperationStopped, localMachineName); cmdlet.ThrowTerminatingError(error); } // Set the same password to the local machine Dbg.Diagnostics.Assert(newPassword != null, "the newPassword should not be null at this point"); // A direct translation of function NetpManageMachineSecret2 in //depot/winmain/ds/netapi/netjoin/joinutl.c // Initialize the LSA_OBJECT_ATTRIBUTES var lsaAttr = new SAMAPI.LSA_OBJECT_ATTRIBUTES(); lsaAttr.RootDirectory = IntPtr.Zero; lsaAttr.ObjectName = IntPtr.Zero; lsaAttr.Attributes = 0; lsaAttr.SecurityDescriptor = IntPtr.Zero; lsaAttr.SecurityQualityOfService = IntPtr.Zero; lsaAttr.Length = Marshal.SizeOf(typeof(SAMAPI.LSA_OBJECT_ATTRIBUTES)); // Initialize the policy handle and secret handle IntPtr policyHandle = IntPtr.Zero; IntPtr secretHandle = IntPtr.Zero; // Initialize variables for LsaQuerySecret call IntPtr currentPassword = IntPtr.Zero; // Declare the key, newData and currentData var key = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero }; var newData = new SAMAPI.LSA_UNICODE_STRING { Buffer = IntPtr.Zero }; // Initialize the systemName for the localhost var localhost = new SAMAPI.LSA_UNICODE_STRING(); localhost.Buffer = IntPtr.Zero; localhost.Length = 0; localhost.MaximumLength = 0; try { // Open the LSA policy uint ret = SAMAPI.LsaOpenPolicy(ref localhost, ref lsaAttr, (int)SAMAPI.LSA_ACCESS.AllAccess, out policyHandle); if (ret == STATUS_ACCESS_DENIED) { string errMsg = ComputerResources.NeedAdminPrivilegeToResetPassword; ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "UnauthorizedAccessException", ErrorCategory.InvalidOperation, localMachineName); cmdlet.ThrowTerminatingError(error); } if (ret != 0) { ThrowOutLsaError(ret, cmdlet); } // Initialize secret key, new secret SAMAPI.InitLsaString(SecretKey, ref key); SAMAPI.InitLsaString(newPassword, ref newData); bool secretCreated = false; // Open the secret. If the secret is not found, create the secret ret = SAMAPI.LsaOpenSecret(policyHandle, ref key, SECRET_SET_VALUE | SECRET_QUERY_VALUE, out secretHandle); if (ret == STATUS_OBJECT_NAME_NOT_FOUND) { ret = SAMAPI.LsaCreateSecret(policyHandle, ref key, SECRET_SET_VALUE, out secretHandle); secretCreated = true; } if (ret != 0) { ThrowOutLsaError(ret, cmdlet); } SAMAPI.LSA_UNICODE_STRING currentData; // Get the current password if (secretCreated) { // Use the new password as the current one currentData = newData; } else { // Query for the current password ret = SAMAPI.LsaQuerySecret(secretHandle, out currentPassword, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (ret != 0) { ThrowOutLsaError(ret, cmdlet); } currentData = (SAMAPI.LSA_UNICODE_STRING)Marshal.PtrToStructure(currentPassword, typeof(SAMAPI.LSA_UNICODE_STRING)); } ret = SAMAPI.LsaSetSecret(secretHandle, ref newData, ref currentData); if (ret != 0) { ThrowOutLsaError(ret, cmdlet); } } finally { // Release pointers if (currentPassword != IntPtr.Zero) { int releaseResult = SAMAPI.LsaFreeMemory(currentPassword); Dbg.Diagnostics.Assert(releaseResult == 0, "LsaFreeMemory returned non-zero value"); } // Release handles if (policyHandle != IntPtr.Zero) { int releaseResult = SAMAPI.LsaClose(policyHandle); Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value"); } if (secretHandle != IntPtr.Zero) { int releaseResult = SAMAPI.LsaClose(secretHandle); Dbg.Diagnostics.Assert(releaseResult == 0, "LsaClose returned non-zero value"); } // Release LSA_UNICODE_STRING SAMAPI.FreeLsaString(ref key); SAMAPI.FreeLsaString(ref newData); } }
private SearchResult FindCurrentUser(string[] attribsToLoad) { //parse the current user's logon name as search key string sFilter = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", User.Identity.Name.Split(new char[] { '\\' })[1]); DirectoryEntry searchRoot = new DirectoryEntry(adsPath, null, null, AuthenticationTypes.Secure);//sets search root to adsPath using (searchRoot)//this just pulls the infomation for the current user { string user = Environment.UserName; DirectorySearcher ds = new DirectorySearcher(searchRoot, sFilter, attribsToLoad, SearchScope.Subtree); ds.SizeLimit = 1; return ds.FindOne(); } }
/// <summary> /// Get User Account Control flags. /// </summary> /// <param name="item"></param> /// <returns></returns> /// <remarks> /// References: /// https://msdn.microsoft.com/en-us/library/cc223145.aspx /// https://msdn.microsoft.com/en-us/library/cc223393.aspx /// https://msdn.microsoft.com/en-us/library/ms677840(v=vs.85).aspx /// https://technet.microsoft.com/en-us/library/ee198831.aspx /// http://stackoverflow.com/questions/25213146/constructed-attributes-in-active-directory-global-catalog-get-password-expiry-f /// </remarks> public static Int32 Get_userAccountControl(DirectoryEntry item, out Int64 PwdExpComputed) { Int32 uac = 0; PwdExpComputed = 0; SearchResult res = null; try { // Need to query AD for every user to get up to date msDS-User-Account-Control-Computed. DirectorySearcher srch = new DirectorySearcher(item, "(objectClass=*)", new string[] { "userAccountControl", "msDS-User-Account-Control-Computed", "msDS-UserPasswordExpiryTimeComputed" }, SearchScope.Base); if ((res = srch.FindOne()) == null) return uac; Int32 AC1 = 0, AC2 = 0; if (res.Properties.Contains("userAccountControl")) AC1 = Convert.ToInt32(res.Properties["userAccountControl"][0]); if (res.Properties.Contains("msDS-User-Account-Control-Computed")) AC2 = Convert.ToInt32(res.Properties["msDS-User-Account-Control-Computed"][0]); uac = AC1 | AC2; if (IsUserCannotChangePassword(item)) uac |= 0x40; PwdExpComputed = GetFileTime(res, "msDS-UserPasswordExpiryTimeComputed"); } catch (Exception ex) { SqlContext.Pipe.Send("Warning: Get_userAccountControl failed for user (" + GetDistinguishedName(item) + ")" + " Exception: " + ex.Message); } return uac; }
public bool ValidateCredentialsAndLogon(string userName, string password) { var path = Domain.GetComputerDomain().GetDirectoryEntry().Path; var domain = Domain.GetComputerDomain().Name; var domainAndUsername = domain + @"\" + userName; var entry = new DirectoryEntry(path, domainAndUsername, password); try { //Bind to the native AdsObject to force authentication. var search = new DirectorySearcher(entry) { Filter = "(SAMAccountName=" + userName + ")" }; search.PropertiesToLoad.Add("cn"); var result = search.FindOne(); if (null == result) { return false; } } catch (Exception) { return false; } return true; }