private void btnLogin_Click(object sender, EventArgs e) { if (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0) { MessageBox.Show("用户名或者密码不能为空。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string directoryPath = "LDAP://" + GetDomainName(); string domainAndUsername = directoryPath + txtUserName.Text; try { DirectoryEntry entry = new DirectoryEntry(directoryPath, txtUserName.Text, txtPassword.Text); DirectorySearcher search = new DirectorySearcher(entry); SearchResult result = search.FindOne(); MessageBox.Show("登录成功。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { // 如果用户名或者密码不正确,也会抛出异常。 MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop); } }
protected override void SetPropertyValue(IOguObject srcOguObject, string srcPropertyName, DirectoryEntry entry, string targetPropertyName, string context, SetterContext setterContext) { string srcPropertyValue = GetNormalizeddSourceValue(srcOguObject, srcPropertyName, context); string targetPropertyValue = GetNormalizeddTargetValue(entry, targetPropertyName, context); if (srcPropertyValue != targetPropertyValue) { //entry.CommitChanges(); try { entry.Properties[targetPropertyName].Value = srcOguObject.Properties[srcPropertyName]; // entry.CommitChanges(); } catch (DirectoryServicesCOMException ex) { if (ex.ErrorCode == -2147019886) { //对象已存在 entry.Properties[targetPropertyName].Value = "TMP" + Environment.TickCount.ToString("X"); entry.CommitChanges(); SynchronizeContext.Current.DelayActions.Add(new DelayRenameCodeNameAction(srcOguObject, srcPropertyName, entry.NativeGuid, targetPropertyName)); } else { throw; } } } }
public bool IsAuthenticated(string domain, string username, string pwd) { 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 ((result == null)) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = Convert.ToString(result.Properties["cn"][0]); } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return true; }
private static SearchResultCollection GetUsers(DirectoryEntry ad, string ldapFilter) { var search = new DirectorySearcher(ad, ldapFilter); search.SearchScope = AppSettings.GeneralSettings.SearchScope; var results = search.FindAll(); return results; }
private static TreeNode CreateTreeNode(DirectoryEntry directoryEntry) { InitAllowedSchemaClass(); if (allowedSchemaClass.Contains(directoryEntry.SchemaClassName)) { TreeNode node = new TreeNode(); if (directoryEntry.SchemaClassName.Equals(IISConstants.TYPE_WEBSERVER, StringComparison.InvariantCulture)) { node.Text = IISConstants.GetProperty<string>(directoryEntry, IISConstants.PROPERTY_WEBSITE_NAME); } else { node.Text = directoryEntry.Name; } node.ImageKey = directoryEntry.SchemaClassName; node.SelectedImageKey = directoryEntry.SchemaClassName; node.Tag = directoryEntry.Path; foreach (DirectoryEntry child in directoryEntry.Children) { TreeNode childNode = CreateTreeNode(child); if (childNode != null) node.Nodes.Add(childNode); } return node; } else { return null; } }
/// <summary> /// �������û������� /// </summary> /// <param name="UserName">���û���</param> /// <param name="OldPassword">������</param> /// <param name="NewPassword">������</param> /// <param name="DomainName">DNS����</param> /// <returns>�ɹ������棬���ɹ����ؼ�</returns> public static bool ChangePassword(string UserName, string OldPassword, string NewPassword, string DomainName) { try { string UserPrincipalName = UserName + "@" + DomainName; DirectoryEntry deRootDSE = new DirectoryEntry("LDAP://RootDSE", UserPrincipalName, OldPassword, AuthenticationTypes.Secure); DirectoryEntry deDomain = new DirectoryEntry("LDAP://" + deRootDSE.Properties["defaultNamingContext"].Value.ToString(), UserPrincipalName, OldPassword, AuthenticationTypes.Secure); DirectorySearcher dsSearcher = new DirectorySearcher(); dsSearcher.SearchRoot = deDomain; dsSearcher.SearchScope = SearchScope.Subtree; dsSearcher.Filter = "(userPrincipalName=" + UserPrincipalName + ")"; SearchResult srResult = dsSearcher.FindOne(); if (srResult != null) { DirectoryEntry deUser = new DirectoryEntry(srResult.GetDirectoryEntry().Path, UserPrincipalName, OldPassword, AuthenticationTypes.Secure); deUser.Invoke("ChangePassword", new object[] { OldPassword, NewPassword }); deUser.CommitChanges(); return true; } else return false; } catch //(Exception ex) { return false;// ex.Message; } }
public static Task Test() { return Task.Run(() => { string strServerDNS = "ldap.hp.com:389"; string strSearchBaseDN = "ou=Email,ou=Services,o=hp.com"; string strLDAPPath; strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN; DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous); DirectorySearcher searcher = new DirectorySearcher(objDirEntry); SearchResult result = null; searcher.Filter = "[email protected]"; searcher.PropertiesToLoad.Add("ntUserDomainId"); searcher.ClientTimeout = TimeSpan.FromSeconds(20); try { result = searcher.FindOne(); } catch (Exception ex) { } finally { searcher.Dispose(); } }); }
//http://support.microsoft.com/kb/306273 //http://www.gotdotnet.ru/blogs/sergeyhomyuk/10326/ public static String CreateLocalUser(string login, string fullName, string password, TServer Server) { try { DirectoryEntry root = new DirectoryEntry(string.Format("WinNT://{0},computer", Server.IP)); using (DirectoryEntry user = root.Children.Add(login, "user")) { user.Properties["FullName"].Value = fullName; user.Properties["Description"].Value = DateTime.Now.ToString(); user.Invoke("SetPassword", new object[] { password }); user.CommitChanges(); string UserPath = user.Path.ToString().Replace(Server.IP, Server.Name); DirectoryEntry grp = root.Children.Find("Спутник ОТЦ3 Челябинск", "group"); if (grp != null) { grp.Invoke("Add", new object[] { UserPath }); } return String.Format("Пользователь {0} создан на сервере {1}.", login, Server); } } catch (COMException e) { return String.Format("Пользователь {0} не создан на сервере {1}. Ошибка: '{2}'", login, Server,e.Message); } }
static string GetProperty(string id, string propertyName) { using (var de = new DirectoryEntry($"WinNT://{Environment.UserDomainName}/{id}")) { return de.Properties[propertyName].Value.ToString(); } }
public LdapUser(DirectoryEntry adentry, String userName, LdapSettings ldapSettings) { userid = new LdapAttribute("userid", userName); DirectorySearcher ds = new DirectorySearcher(adentry); ds.Filter = "(&(sAMAccountName=" + userName + "))"; SearchResult result = ds.FindOne(); DirectoryEntry ent = null; if (result != null) { ent = result.GetDirectoryEntry(); } if (ent != null) { if (ent.Properties["cn"].Value != null) { commonname = new LdapAttribute("commonname", ent.Properties["cn"].Value.ToString()); } else { commonname = new LdapAttribute("commonname", userName); } if (ent.Properties["mail"].Value != null) { email = new LdapAttribute("email", ent.Properties["mail"].Value.ToString()); } else { email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain); } } }
private static string GetFullNameFromActiveDirectory(string username) { // got from http://milanl.blogspot.com/2008/08/retrieve-full-name-from-active.html string strDomain; string strName; // Parse the string to check if domain name is present. int idx = username.IndexOf('\\'); if (idx == -1) { idx = username.IndexOf('@'); } if (idx != -1) { strDomain = username.Substring(0, idx); strName = username.Substring(idx + 1); } else { strDomain = Environment.MachineName; strName = username; } DirectoryEntry obDirEntry = null; obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName); System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties; string name = (string)coll["FullName"].Value; return string.IsNullOrWhiteSpace(name) ? username : strName; }
private static string GetDomainName(string dnsName) { string defaultNamingContext; string rootDomainNamingContext; using (var rootDSE = new DirectoryEntry("LDAP://RootDSE")) { defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); rootDomainNamingContext = rootDSE.Properties["rootDomainNamingContext"].Value.ToString(); } using ( var domainRoot = defaultNamingContext.Equals(rootDomainNamingContext, StringComparison.InvariantCultureIgnoreCase) ? new DirectoryEntry($"LDAP://CN=Partitions,CN=Configuration,{defaultNamingContext}") : new DirectoryEntry($"LDAP://CN=Partitions,CN=Configuration,{rootDomainNamingContext}")) { try { foreach (DirectoryEntry c in domainRoot.Children) { try { if (c.Properties["dnsRoot"].Value.ToString().Equals(dnsName, StringComparison.InvariantCultureIgnoreCase)) { return c.Properties["NetBIOSName"].Value.ToString(); } } // ReSharper disable once EmptyGeneralCatchClause catch {} } } // ReSharper disable once EmptyGeneralCatchClause catch {} } return string.Empty; }
internal SAMGroupsSet(UnsafeNativeMethods.IADsMembers iADsMembers, SAMStoreCtx storeCtx, DirectoryEntry ctxBase) { this.atBeginning = true; this.groupsEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); this.storeCtx = storeCtx; this.ctxBase = ctxBase; }
public ArrayList GetDomains() { ArrayList arrDomains = new ArrayList(); DirectoryEntry ParentEntry = new DirectoryEntry(); try { ParentEntry.Path = "WinNT:"; foreach (DirectoryEntry childEntry in ParentEntry.Children) { switch (childEntry.SchemaClassName) { case "Domain": { arrDomains.Add(childEntry.Name); break; } default: { break; } } } } catch (Exception e) { } finally { ParentEntry = null; } return arrDomains; }
/// <summary> /// 创建虚拟目录 /// </summary> public static void CreateVirtual() { DirectoryEntry currentSite = SiteInfo.Current.CurrentSite;//站点或虚拟目录 if (currentSite.SchemaClassName == "IIsWebServer") currentSite = new DirectoryEntry(currentSite.Path + "/root"); DirectoryEntry vdEntry = currentSite.Children.Add(SiteInfo.Current.VirtualName, "IIsWebVirtualDir"); vdEntry.CommitChanges(); //属性设置 vdEntry.Properties["Path"][0] = SiteInfo.Current.WebPath; vdEntry.Properties["AppFriendlyName"].Value = SiteInfo.Current.VirtualName; vdEntry.Properties["DefaultDoc"].Value = SiteInfo.Current.DefaultDoc; if ((int)SiteInfo.Current.IVersion >= (int)IISVersion.IIS6) vdEntry.Properties["AppPoolId"][0] = SiteInfo.Current.AppPool; vdEntry.Properties["AppRoot"][0] = vdEntry.Path.Replace("IIS://" + SiteInfo.Current.DomainName, "/LM");//路径特殊处理 创建应用程序 vdEntry.Invoke("AppCreate", true); vdEntry.Properties["AccessFlags"][0] = 513; vdEntry.Properties["AuthFlags"][0] = 1; vdEntry.Properties["AnonymousUserName"][0] = SiteInfo.Current.UserName_iusr; vdEntry.Properties["AnonymousUserPass"][0] = SiteInfo.Current.PassWord_iusr; string ScriptMaps = ".aspx," + System.Environment.GetFolderPath(System.Environment.SpecialFolder.System).ToUpper().Replace("SYSTEM32", "") + @"microsoft.net\framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG"; if (!vdEntry.Properties["ScriptMaps"].Contains(ScriptMaps)) vdEntry.Properties["ScriptMaps"][0] = ScriptMaps; if ((int)SiteInfo.Current.IVersion >= (int)IISVersion.IIS6) CreateAppPool(); AspNetRegIIS("-s " + vdEntry.Path.Replace("IIS://" + SiteInfo.Current.DomainName + "/", ""));//路径特殊处理 vdEntry.CommitChanges(); vdEntry.RefreshCache(); currentSite.CommitChanges(); currentSite.RefreshCache(); }
protected bool AddUserToLocalGroup(string user, string groupName, string domainName, string machine) { bool reponse = false; try { string userPath = string.Format("WinNT://{0}/{1},user", domainName, user); string groupPath = string.Format("WinNT://{0}/{1},group", machine, groupName); using (DirectoryEntry groupe = new DirectoryEntry(groupPath)) { groupe.Invoke("Add", userPath); groupe.CommitChanges(); groupe.Close(); } } catch (System.DirectoryServices.DirectoryServicesCOMException E) { Log(Level.Error, E.Message.ToString()); } return reponse; }
public static Type GetPropertyType(DirectoryEntry entry, string propertyName) { if( entry != null && !string.IsNullOrEmpty(propertyName) && entry.Properties != null) return entry.Properties[propertyName] == null ? typeof(object) : entry.Properties[propertyName].Value.GetType(); return null; }
public void TestFixtureTearDown() { if (de != null) de.Dispose (); de = null; }
/// <summary> /// Creates a new user account /// </summary> /// <param name="name">User login name</param> /// <param name="password">User password</param> /// <param name="fullName">User full name</param> /// <param name="isAdmin">flag as admin</param> /// <returns>returns true when user is successfully created</returns> public static bool Create(string name, string password, string fullName = "", bool isAdmin = false) { try { var dirEntry = new DirectoryEntry("WinNT://localhost"); DirectoryEntries entries = dirEntry.Children; DirectoryEntry newUser = entries.Add(name, "user"); newUser.Properties["FullName"].Add(fullName); newUser.Invoke("SetPassword", password); newUser.CommitChanges(); // Remove the if condition along with the else to create user account in "user" group. DirectoryEntry grp; grp = dirEntry.Children.Find(UserGroup, "group"); grp.Invoke("Add", new object[] {newUser.Path}); if (isAdmin) { grp = dirEntry.Children.Find(AdminGroup, "group"); grp.Invoke("Add", new object[] {newUser.Path}); } } catch (Exception ex) { Logger.Instance.WriteGlobal("Failed to add new user: {0}", name); DebugHelper.Exception(ex); return false; } return (isAdmin && ExistsAsAdmin(name)) || (Exists(name)); }
static public void getGrups(string username, string group_Admin) { try { // string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", "afanasievdv"); string domain = "isea.ru"; string[] properties = new string[] { "fullname" }; // username = "******"; DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure); DirectorySearcher dirsearcher = new DirectorySearcher(adRoot); dirsearcher.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username); dirsearcher.PropertiesToLoad.Add("memberOf"); int propCount; SearchResult dirSearchResults = dirsearcher.FindOne(); propCount = dirSearchResults.Properties["memberOf"].Count; DirectoryEntry directoryEntry = dirSearchResults.GetDirectoryEntry(); // string dn, equalsIndex, commaIndex; PropertyValueCollection groups = directoryEntry.Properties["memberOf"]; foreach (string g in groups) { string group = g.Split('=')[1].Split(',')[0]; System.Diagnostics.Debug.WriteLine(group); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } }
public static object GetProperty(DirectoryEntry objectDE, string property) { if (objectDE == null) { throw new ArgumentNullException("objectDE", "Value cannot be null"); } if (string.IsNullOrEmpty(property)) { throw new ArgumentNullException("property", "Value cannot be null"); } switch (property) { case "whenCreated": case "whenChanged": if (objectDE.Properties.Contains(property)) { return objectDE.Properties[property].Value; } break; default: return null; } return null; }
public void CreateFtpServerVirtualDirectory(int iFtpSiteID, string sVirtualDirectoryName, string sPath, bool bCanRead, bool bCanWrite, bool isRoot) { DirectoryEntry directoryEntry1; DirectoryEntry directoryEntry2; if (!isRoot) { directoryEntry1 = new DirectoryEntry(String.Concat("IIS://localhost/MSFTPSVC/", iFtpSiteID, "/ROOT")); var locals = new object[] {"IISFtpVirtualDir", sVirtualDirectoryName}; directoryEntry2 = (DirectoryEntry) directoryEntry1.Invoke("Create", locals); } else { directoryEntry1 = new DirectoryEntry(String.Concat("IIS://localhost/MSFTPSVC/", iFtpSiteID)); var locals = new object[] {"IISFtpVirtualDir", "ROOT"}; directoryEntry2 = (DirectoryEntry) directoryEntry1.Invoke("Create", locals); } directoryEntry2.Properties["Path"][0] = sPath; int i = 0; if (bCanRead) { i++; } if (bCanWrite) { i += 2; } directoryEntry2.Properties["AccessFlags"][0] = i; directoryEntry2.CommitChanges(); directoryEntry1.Invoke("SetInfo", new object[0]); directoryEntry1.CommitChanges(); directoryEntry1.Dispose(); }
public List<User> GetADUsers() { try { List<User> AdUsers = new List<User>(); string domainPath = "LDAP://OU=Users,OU=Cobweb Solutions Ltd,DC=cobwebsolutions,DC=com"; DirectoryEntry searchroot = new DirectoryEntry(domainPath); DirectorySearcher search = new DirectorySearcher(searchroot); search.Filter = "(&(objectClass=user)(objectCategory=person))"; search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("displayname"); SearchResult result; SearchResultCollection resultCol = search.FindAll(); if (resultCol != null) { for (int i = 0; i < resultCol.Count; i++) { result = resultCol[i]; User adUser = new User(); adUser.DisplayName = (string)result.Properties["displayname"][0]; adUser.UserName = (string)result.Properties["samaccountname"][0]; AdUsers.Add(adUser); } } return AdUsers; } catch (Exception ex) { return null; } }
// ------------------------------------------------------------------------------- // Look in virtual subdirectories. protected override void SearchSubDirectories(string nameAdsiDir) { if ( CompModSwitches.DynamicDiscoverySearcher.TraceVerbose ) Debug.WriteLine( "DynamicVirtualDiscoSearcher.SearchSubDirectories(): nameAdsiDir=" + nameAdsiDir); DirectoryEntry vdir = (DirectoryEntry)Adsi[nameAdsiDir]; //may be already bound if (vdir == null) { if ( !DirectoryEntry.Exists(nameAdsiDir) ) return; vdir = new DirectoryEntry(nameAdsiDir); Adsi[nameAdsiDir] = vdir; } foreach (DirectoryEntry obj in vdir.Children) { DirectoryEntry child = (DirectoryEntry)Adsi[obj.Path]; if (child == null) { child = obj; Adsi[obj.Path] = obj; } else { obj.Dispose(); } AppSettings settings = GetAppSettings(child); if (settings != null) { ScanDirectory(child.Path); //go down ADSI path } } }
internal static IEnumerable<BplRole> GetClientRoles(string loginName) { try { using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) { using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName)) { try { var groups = user.GetAuthorizationGroups(); var roles = groups.Select(g => BplRole.Get(g.Name)).Where(r => r != null).ToArray(); return roles; } catch (PrincipalOperationException pex) { Log.Exception(pex, Severity.Warning, "Unable to retrive client roles on trusted domain. Fall back to untrusted."); } //TK: Fallback to untrusted communication or DNS issues. I do not believe i need to do this! var usr = (DirectoryEntry)user.GetUnderlyingObject(); var dgroups = usr.Invoke("Groups"); var droles = new List<BplRole>(); foreach (var g in (IEnumerable)dgroups) { var ge = new DirectoryEntry(g); var role = BplRole.Get(ge.Name.RemoveAll("CN=")); if (role != null) { droles.Add(role); } } return droles; } } } catch (Exception e) { Log.Exception(e, "Unable to retrive client roles"); } return null; }
public static List<string> GetDomainList2() { List<string> domainList = new List<string>(); string sRootDomain; System.DirectoryServices.DirectoryEntry deRootDSE; System.DirectoryServices.DirectoryEntry deSearchRoot; System.DirectoryServices.DirectorySearcher dsFindDomains; System.DirectoryServices.SearchResultCollection srcResults; deRootDSE = new System.DirectoryServices.DirectoryEntry("GC://RootDSE"); sRootDomain = "GC://" + deRootDSE.Properties["rootDomainNamingContext"].Value.ToString(); deSearchRoot = new System.DirectoryServices.DirectoryEntry(sRootDomain); dsFindDomains = new System.DirectoryServices.DirectorySearcher(deSearchRoot); dsFindDomains.Filter = "(objectCategory=domainDNS)"; dsFindDomains.SearchScope = System.DirectoryServices.SearchScope.Subtree; srcResults = dsFindDomains.FindAll(); foreach (System.DirectoryServices.SearchResult srDomain in srcResults) { domainList.Add(srDomain.Properties["name"][0].ToString()); } return domainList; }
public DirectoryEntryWrapper(DirectoryEntry directoryEntry) { if(directoryEntry == null) throw new ArgumentNullException("directoryEntry"); this._directoryEntry = directoryEntry; }
private static string GetFullName(string username) { try { if (_usernameMappings.ContainsKey(username)) return _usernameMappings[username]; var de = new DirectoryEntry("WinNT://" + username.Replace("\\", "/")); var fullname = de.Properties["fullName"].Value.ToString(); var parts = fullname.Split(','); if (parts.Length >= 2) { var correctedName = string.Format("{0} {1}", parts[1].Trim(), parts[0].Trim()); fullname = correctedName; } _usernameMappings.Add(username, fullname); var formatter = new BinaryFormatter(); using(var fs = new FileStream(USER_MAPPING_FILENAME, FileMode.OpenOrCreate)) formatter.Serialize(fs, _usernameMappings); return fullname; } catch { return username; } }
public static void SetProperties(DirectoryEntry objectDE, Dictionary<string, object> properties) { if (objectDE == null) { throw new NullReferenceException("Parametr <objectDE> cannot be null"); } if (properties == null) { throw new NullReferenceException("Parametr <properties> cannot be null"); } foreach (var _key in properties.Keys) { try { switch (_key) { case "info": case "extensionAttribute1": objectDE.Properties[_key].Value = (string)properties[_key]; break; } objectDE.CommitChanges(); } catch(Exception ex) { throw new Exception("Cannot set DirectoryEntry property <" + _key + ">"); } } }
private void RequesterEmail_comboBox_SelectedIndexChanged(object sender, EventArgs e) { // Get user first name and last name by email string mail = RequesterEmail_comboBox.Text; DirectoryEntry entry = new DirectoryEntry(); DirectorySearcher adsearcher = new DirectorySearcher(entry); adsearcher.Filter = "(&(objectClass=user)(mail=" + mail + "))"; adsearcher.PropertiesToLoad.Add("givenName"); adsearcher.PropertiesToLoad.Add("sn"); adsearcher.PropertiesToLoad.Add("mail"); SearchResult result = adsearcher.FindOne(); if (result == null) MessageBox.Show("Email Does Not Exist !!" + Environment.NewLine + "Please Check Your Spelling !!"); if (result != null) { DirectoryEntry employee = result.GetDirectoryEntry(); string FirstName = employee.Properties["givenName"].Value.ToString(); string LastName = employee.Properties["sn"].Value.ToString(); RequesterFirstName_txtBox.Text = FirstName; RequesterLastName_txtBox.Text = LastName; } }
public void LDAPQuery(string ldapbase, string filter, int limit) { Boolean islimit = false; if (limit > 0) { islimit = true; } //DirectoryEntry deRoot = new DirectoryEntry("LDAP://W2K8DC/dc=stufus,dc=lan"); DirectoryEntry deRoot = new DirectoryEntry(ldapbase); DirectorySearcher dsFindUser = new DirectorySearcher(deRoot); dsFindUser.SearchScope = SearchScope.Subtree; if (islimit == false) { Console.Out.WriteLine("LDAP Search for '{0}' without a results limit", filter); } else { Console.Out.WriteLine("LDAP Search for '{0}' with a limit of {1} {2}", filter, limit, (limit == 1)?"result":"results"); } dsFindUser.Filter = filter; SearchResultCollection result = dsFindUser.FindAll(); int number_of_results = result.Count; Console.Out.WriteLine("Total: {0} result{1}", number_of_results, (number_of_results == 1)?"":"s"); if (result != null) { foreach (System.DirectoryServices.SearchResult resEnt in result) { Console.Out.WriteLine("------------------------------------"); System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry(); foreach (string prop in de.Properties.PropertyNames) { try { int num_items = de.Properties[prop].Count; foreach (string pval in de.Properties[prop]) { Console.Out.WriteLine("{0}[{1}]: {2}", prop, num_items, pval); } } catch { // TODO some attributes can't be casted to a string - so work through them //Console.Out.WriteLine("{0}=(ERROR)", prop); } } if (islimit == true) { limit--; if (limit == 0) { return; } } } } }
public static DirectoryEntry DirectoryEntry(string strDN) { //DirectoryEntry myUser =new System.DirectoryServices.DirectoryEntry("LDAP://PCDC1.dms.local/" + strDN, account, password, AuthenticationTypes.Secure); DirectoryEntry myUser = new System.DirectoryServices.DirectoryEntry("LDAP://PCDC1.dms.local/" + strDN); return myUser; }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; tainted_2 = "hardcoded"; tainted_3 = tainted_2; if ((Math.Sqrt(42) >= 42)) { StringBuilder escape = new StringBuilder(); for (int i = 0; i < tainted_2.Length; ++i) { char current = tainted_2[i]; switch (current) { case '\\': escape.Append(@"\5c"); break; case '*': escape.Append(@"\2a"); break; case '(': escape.Append(@"\28"); break; case ')': escape.Append(@"\29"); break; case '\u0000': escape.Append(@"\00"); break; case '/': escape.Append(@"\2f"); break; default: escape.Append(current); break; } } tainted_3 = escape.ToString(); } else { {} } string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_0 = null; string tainted_1 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_0 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_1 = tainted_0; string pattern = @"/^[0-9]*$/"; Regex r = new Regex(pattern); Match m = r.Match(tainted_0); if (!m.Success) { tainted_1 = ""; } else { tainted_1 = tainted_0; } //flaw string query = "(&(objectClass=person)(sn=" + tainted_1 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; switch (6) { case (6): break; default: string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + ";"; Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch))); tainted_3 = r.Replace(tainted_2, ""); break; } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; if ((4 + 2 <= 42)) { {} } else if (!(4 + 2 <= 42)) { StringBuilder escape = new StringBuilder(); for (int i = 0; i < tainted_2.Length; ++i) { char current = tainted_2[i]; switch (current) { case '\\': escape.Append(@"\5c"); break; case '*': escape.Append(@"\2a"); break; case '(': escape.Append(@"\28"); break; case ')': escape.Append(@"\29"); break; case '\u0000': escape.Append(@"\00"); break; case '/': escape.Append(@"\2f"); break; default: escape.Append(current); break; } } tainted_3 = escape.ToString(); } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
private System.DirectoryServices.DirectoryEntry GetAppPoolDirectoryEntry() { System.DirectoryServices.DirectoryEntry appPoolRoot = new System.DirectoryServices.DirectoryEntry(string.Format("IIS://{0}/W3SVC/AppPools", _server)); return(appPoolRoot); }
private DirectoryEntry GetWebSiteDirectoryEntry(string siteID) { System.DirectoryServices.DirectoryEntry webSiteDirectory = new System.DirectoryServices.DirectoryEntry(string.Format("IIS://{0}/W3SVC/{1}/Root", _server, siteID)); return(webSiteDirectory); }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; Process process = new Process(); process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = "-c 'cat /tmp/tainted.txt'"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); using (StreamReader reader = process.StandardOutput) { tainted_2 = reader.ReadToEnd(); process.WaitForExit(); process.Close(); } tainted_3 = tainted_2; if ((Math.Sqrt(42) <= 42)) { StringBuilder text = new StringBuilder(tainted_2); text.Replace("&", "&"); text.Replace("'", "'"); text.Replace(@"""", """); text.Replace("<", "<"); text.Replace(">", ">"); tainted_3 = text.ToString(); } else { {} } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
public void saveProperties(FormCollection props) { System.DirectoryServices.DirectoryEntry user = new System.DirectoryServices.DirectoryEntry("LDAP://" + props["DistinguishedName"]); if (string.IsNullOrEmpty(props["GivenName"])) { props["GivenName"] = "FirstName"; } if (string.IsNullOrEmpty(props["SurName"])) { props["SurName"] = "LastName"; } if (string.IsNullOrEmpty(props["DisplayName"])) { props["DisplayName"] = props["GivenName"] + " " + props["SurName"]; } if (!string.IsNullOrEmpty(props["GivenName"])) { if (user.Properties.Contains("givenName")) { user.Properties["givenName"][0] = props["GivenName"]; } else { user.Properties["givenName"].Add(props["GivenName"]); } } else { user.Properties["givenName"].Clear(); } if (!string.IsNullOrEmpty(props["SurName"])) { if (user.Properties.Contains("sn")) { user.Properties["sn"][0] = props["SurName"]; } else { user.Properties["sn"].Add(props["SurName"]); } } else { user.Properties["sn"].Clear(); } if (!string.IsNullOrEmpty(props["DisplayName"])) { if (user.Properties.Contains("displayName")) { user.Properties["displayName"][0] = props["DisplayName"]; } else { user.Properties["displayName"].Add(props["DisplayName"]); } } else { //user.Properties["displayName"].Clear(); } if (!string.IsNullOrEmpty(props["TelephoneNumber"])) { if (user.Properties.Contains("telephoneNumber")) { user.Properties["telephoneNumber"][0] = props["TelephoneNumber"]; } else { user.Properties["telephoneNumber"].Add(props["TelephoneNumber"]); } } else { user.Properties["telephoneNumber"].Clear(); } if (!string.IsNullOrEmpty(props["Department"])) { if (user.Properties.Contains("department")) { user.Properties["department"][0] = props["Department"]; } else { user.Properties["department"].Add(props["Department"]); } } else { user.Properties["department"].Clear(); } if (!string.IsNullOrEmpty(props["Office"])) { if (user.Properties.Contains("physicalDeliveryOfficeName")) { user.Properties["physicalDeliveryOfficeName"][0] = props["Office"]; } else { user.Properties["physicalDeliveryOfficeName"].Add(props["Office"]); } } else { user.Properties["physicalDeliveryOfficeName"].Clear(); } if (!string.IsNullOrEmpty(props["Title"])) { if (user.Properties.Contains("title")) { user.Properties["title"][0] = props["Title"]; } else { user.Properties["title"].Add(props["Title"]); } } else { user.Properties["title"].Clear(); } // Access resources while impersonating. user.CommitChanges(); }
/// <summary> /// Creates a virtual directory. If the virtual directory already exists it deletes it and recreates it. /// </summary> /// <param name="siteID">The site ID where the virtual directory should exist</param> /// <param name="virDirName">The virtual directory name, I.E. CEDC or SP</param> /// <param name="path">The root of the virtual directory, where the files exist.</param> /// <param name="appPoolName">The application pool that this virtual directory runs on</param> /// <param name="authMode">The Authentication Mode, Windows or Forms</param> /// <returns></returns> /// <remarks></remarks> public bool CreateVirtualDir(string siteID, string virDirName, string path, string appPoolName, AuthMode authMode) { System.DirectoryServices.DirectoryEntry IISSchema = new System.DirectoryServices.DirectoryEntry("IIS://" + _server + "/Schema/AppIsolated"); bool CanCreate = !(IISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN"); IISSchema.Dispose(); if (CanCreate) { bool PathCreated = false; try { System.DirectoryServices.DirectoryEntry IISAdmin = new System.DirectoryServices.DirectoryEntry(string.Format("IIS://{0}/W3SVC/{1}/Root", _server, siteID)); //make sure folder exists if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); PathCreated = true; } //If the virtual directory already exists then delete it foreach (System.DirectoryServices.DirectoryEntry VD in IISAdmin.Children) { if (VD.Name == virDirName) { IISAdmin.Invoke("Delete", new string[] { VD.SchemaClassName, virDirName }); IISAdmin.CommitChanges(); break; // TODO: might not be correct. Was : Exit For } } //Create and setup new virtual directory System.DirectoryServices.DirectoryEntry VDir = IISAdmin.Children.Add(virDirName, "IIsWebVirtualDir"); VDir.Properties["Path"][0] = path; VDir.Properties["AppFriendlyName"][0] = virDirName; VDir.Properties["EnableDirBrowsing"][0] = false; VDir.Properties["AccessRead"][0] = true; VDir.Properties["AccessExecute"][0] = true; VDir.Properties["AccessWrite"][0] = false; VDir.Properties["AccessScript"][0] = true; VDir.Properties["AuthNTLM"][0] = true; VDir.Properties["EnableDefaultDoc"][0] = true; VDir.Properties["DefaultDoc"][0] = "default.htm,default.aspx,default.asp"; VDir.Properties["AspEnableParentPaths"][0] = true; VDir.Properties["AuthFlags"][0] = GetAuthFlags(authMode); VDir.CommitChanges(); //the following are acceptable params //INPROC = 0 //OUTPROC = 1 //POOLED = 2 VDir.Invoke("AppCreate", 1); AssignVirtualDirectoryToAppPool(siteID, virDirName, appPoolName); } catch (Exception Ex) { if (PathCreated) { System.IO.Directory.Delete(path); } throw Ex; } return(true); } else { return(false); } }
public static void Main(string[] args) { string tainted_2 = null; string tainted_3 = null; string tainted_1 = null; tainted_1 = Console.ReadLine(); tainted_3 = tainted_1; string[] arr_1 = new string[4]; // declaring array //Storing value in array element arr_1[0] = null; arr_1[1] = null; arr_1[2] = null; arr_1[3] = tainted_1; foreach (string val_1 in arr_1) { if (val_1 != null) { tainted_2 = val_1; string pattern = @"/^[0-9]*$/"; Regex r = new Regex(pattern); Match m = r.Match(tainted_2); if (!m.Success) { tainted_3 = ""; } else { tainted_3 = tainted_2; } } } //flaw string query = "(&(objectClass=person)(sn=" + tainted_3 + "))"; string strConnect = "LDAP://my.site.com/o=site,c=com"; using (System.DirectoryServices.DirectoryEntry CN_Main = new System.DirectoryServices.DirectoryEntry(strConnect)){ string strResult = ""; System.DirectoryServices.DirectorySearcher DirSearcher = new System.DirectoryServices.DirectorySearcher(CN_Main, query); System.DirectoryServices.DirectoryEntry CN_Result; CN_Main.AuthenticationType = AuthenticationTypes.None; foreach (System.DirectoryServices.SearchResult ResultSearch in DirSearcher.FindAll()) { if (ResultSearch != null) { CN_Result = ResultSearch.GetDirectoryEntry(); if ((string)CN_Result.Properties["userclass"][0] == "noname") { strResult = strResult + "Name : " + CN_Result.InvokeGet("sn"); } } } Console.WriteLine(strResult); } }
/// <summary> /// Connects to AD and retrieves a parameter of created DirectoryEntry object as /// a verification of object's validity /// </summary> /// <param name="ActiveDirectoryPath">The LDAP path for the ActiveDirectory</param> public void DoADBinding(string activeDirectoryPath) { m_currentDirectory = new DirectoryEntry(activeDirectoryPath); string dirName = m_currentDirectory.Name; }
internal DirectoryEntryHolder(System.DirectoryServices.DirectoryEntry entry) { this.entry = entry; }
private void GetUsedAttributes(string objectDn) { // Get the currently connected LDAP context System.DirectoryServices.DirectoryEntry entry1 = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE"); string domainContext = entry1.Properties["defaultNamingContext"].Value as string; // Use the default naming context as the connected context may not work for searches System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + domainContext); System.DirectoryServices.DirectorySearcher adSearch = new System.DirectoryServices.DirectorySearcher(entry); adSearch.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + objectDn + "))"; adSearch.SearchScope = SearchScope.Subtree; //adSearch.Filter = "(&(objectClass=user)(anr=" + objectDn + "))"; string[] requiredProperties = new string[] { "cn", "userprincipalname", "physicaldeliveryofficename", "distinguishedname", "telephonenumber", "mail", "title", "department", "adspath" }; foreach (String property in requiredProperties) { adSearch.PropertiesToLoad.Add(property); } SearchResult result = adSearch.FindOne(); if (result != null) { foreach (String property in requiredProperties) { if (result.GetDirectoryEntry().Properties[property].Value != null) { switch (property) { case "cn": this._fullname = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "userprincipalname": this._userprincipalname = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "physicaldeliveryofficename": this._physicaldeliveryofficename = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "distinguishedname": this._distinguishedname = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "telephonenumber": this._telephonenumber = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "department": this._department = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "mail": this._email = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "title": this._title = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; case "adspath": this._adspath = result.GetDirectoryEntry().Properties[property].Value.ToString(); break; default: break; } } } } }
/* connect ldap server & create an searcher object */ public static System.DirectoryServices.DirectorySearcher Get_DomainSearcher(Args_Get_DomainSearcher args = null) { if (args == null) { args = new Args_Get_DomainSearcher(); } string TargetDomain = null; string BindServer = null; var userDnsDomain = Environment.GetEnvironmentVariable("USERDNSDOMAIN"); if (args.Domain.IsNotNullOrEmpty()) { TargetDomain = args.Domain; if (userDnsDomain != null && userDnsDomain.Trim() != "") { // see if we can grab the user DNS logon domain from environment variables var UserDomain = userDnsDomain; var logonServer = Environment.GetEnvironmentVariable("LOGONSERVER"); if (logonServer != null && logonServer.Trim() != "" && UserDomain.IsNotNullOrEmpty()) { BindServer = $"{logonServer.Replace(@"\\", "")}.{UserDomain}"; } } } else if (args.Credential != null) { // if not -Domain is specified, but -Credential is, try to retrieve the current domain name with Get-Domain var DomainObject = GetDomain.Get_Domain(new Args_Get_Domain { Credential = args.Credential }); BindServer = DomainObject.PdcRoleOwner.Name; TargetDomain = DomainObject.Name; } else if (userDnsDomain != null && userDnsDomain.Trim() != "") { // see if we can grab the user DNS logon domain from environment variables TargetDomain = userDnsDomain; var logonServer = Environment.GetEnvironmentVariable("LOGONSERVER"); if (logonServer != null && logonServer.Trim() != "" && TargetDomain.IsNotNullOrEmpty()) { BindServer = $"{logonServer.Replace(@"\\", "")}.{TargetDomain}"; } } else { // otherwise, resort to Get-Domain to retrieve the current domain object var DomainObject = GetDomain.Get_Domain(); if (DomainObject == null) { System.Environment.Exit(0); } BindServer = DomainObject.PdcRoleOwner.Name; TargetDomain = DomainObject.Name; } if (args.Server.IsNotNullOrEmpty()) { // if there's not a specified server to bind to, try to pull a logon server from ENV variables BindServer = args.Server; } var SearchString = "LDAP://"; if (BindServer != null && BindServer.Trim() != "") { SearchString += BindServer; if (TargetDomain.IsNotNullOrEmpty()) { SearchString += '/'; } } if (args.SearchBasePrefix.IsNotNullOrEmpty()) { SearchString += args.SearchBasePrefix + @","; } var DN = string.Empty; if (args.SearchBase.IsNotNullOrEmpty()) { if (new Regex(@"^GC://").Match(args.SearchBase).Success) { // if we're searching the global catalog, get the path in the right format DN = args.SearchBase.ToUpper().Trim('/'); SearchString = string.Empty; } else { if (new Regex(@"^LDAP://").Match(args.SearchBase).Success) { if (new Regex(@"LDAP://.+/.+").Match(args.SearchBase).Success) { SearchString = string.Empty; DN = args.SearchBase; } else { DN = args.SearchBase.Substring(7); } } else { DN = args.SearchBase; } } } else { // transform the target domain name into a distinguishedName if an ADS search base is not specified if (TargetDomain != null && TargetDomain.Trim() != "") { DN = $"DC={TargetDomain.Replace(".", ",DC=")}"; } } SearchString += DN; Logger.Write_Verbose($@"[Get-DomainSearcher] search base: {SearchString}"); System.DirectoryServices.DirectorySearcher Searcher = null; if (args.Credential != null) { Logger.Write_Verbose(@"[Get-DomainSearcher] Using alternate credentials for LDAP connection"); // bind to the inital search object using alternate credentials var DomainObject = new System.DirectoryServices.DirectoryEntry(SearchString, args.Credential.UserName, args.Credential.Password); Searcher = new System.DirectoryServices.DirectorySearcher(DomainObject); } else { // bind to the inital object using the current credentials //Searcher = new System.DirectoryServices.DirectorySearcher([ADSI]$SearchString) var DomainObject = new System.DirectoryServices.DirectoryEntry(SearchString); Searcher = new System.DirectoryServices.DirectorySearcher(DomainObject); } Searcher.PageSize = args.ResultPageSize; Searcher.SearchScope = args.SearchScope; Searcher.CacheResults = false; Searcher.ReferralChasing = System.DirectoryServices.ReferralChasingOption.All; if (args.ServerTimeLimit != null) { Searcher.ServerTimeLimit = new TimeSpan(0, 0, args.ServerTimeLimit.Value); } if (args.Tombstone) { Searcher.Tombstone = true; } if (args.LDAPFilter.IsNotNullOrWhiteSpace()) { Searcher.Filter = args.LDAPFilter; } if (args.SecurityMasks != null) { Searcher.SecurityMasks = args.SecurityMasks.Value; } if (args.Properties != null) { // handle an array of properties to load w/ the possibility of comma-separated strings var PropertiesToLoad = new List <string>(); foreach (var item in args.Properties) { PropertiesToLoad.AddRange(item.Split(',')); } Searcher.PropertiesToLoad.AddRange(PropertiesToLoad.ToArray()); } return(Searcher); }
public string validarUsuario(string usuario, string clave, string dominio) { string rpta = ""; DirectoryEntry domain = new DirectoryEntry(dominio); //DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio); using (DirectorySearcher Searcher = new DirectorySearcher(dominio)) { //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan Searcher.Filter = "(SAMAccountName=" + usuario + ")"; // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico Searcher.SearchScope = SearchScope.Subtree; // Start at the top and keep drilling down Searcher.PropertiesToLoad.Add("sAMAccountName"); // Load User ID Searcher.PropertiesToLoad.Add("displayName"); // Load Display Name Searcher.PropertiesToLoad.Add("givenName"); // Load Users first name Searcher.PropertiesToLoad.Add("sn"); // Load Users last name Searcher.PropertiesToLoad.Add("distinguishedName"); // Users Distinguished name Searcher.PropertiesToLoad.Add("proxyAddresses"); // correo del usuario Searcher.PropertiesToLoad.Add("department"); // area de trabajo Searcher.PropertiesToLoad.Add("title"); // rol del usuario Searcher.PropertiesToLoad.Add("userAccountControl"); // Users Distinguished name Searcher.Sort.PropertyName = "sAMAccountName"; // Sort by user ID Searcher.Sort.Direction = System.DirectoryServices.SortDirection.Ascending; // A-Zt) using (var users = Searcher.FindAll()) // Users contains our searh results { if (users.Count > 0) { foreach (SearchResult User in users) // goes throug each user in the search resultsg { //Ambito._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]); //int flagExists = Ambito._estCuentaUsuario & 0x2; //if (flagExists > 0) //{ // rpta = "La cuenta de usuario se encuentra deshabilitada"; //} System.DirectoryServices.DirectoryEntry Entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave); System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry); valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel; try { System.DirectoryServices.SearchResult Results = valSearcher.FindOne(); } catch (Exception ex) { rpta = ex.Message; return(rpta); } //if (User.Properties.Contains("displayName")) //{ // Ambito._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]); //} //if (User.Properties.Contains("title")) //{ // Ambito._rolUsuario = System.Convert.ToString(User.Properties["title"][0]); //} //if (User.Properties.Contains("title")) //{ // Ambito._dptoUsuario = System.Convert.ToString(User.Properties["title"][0]); //} //if (User.Properties.Contains("proxyAddresses")) //{ // Ambito._correoUsuario = System.Convert.ToString(User.Properties["proxyAddresses"][0]); //} //if (User.Properties.Contains("sAMAccountName")) //{ // Ambito.Usuario = System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper(); //} rpta = "OK"; } } else { rpta = "ER"; } } } return(rpta); }
/// <summary> /// 获得DirectoryEntry对象实例,以管理员登陆AD /// </summary> /// <returns></returns> private static DirectoryEntry GetDirectoryObject() { DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure); return(entry); }
// // Summary: // Initializes a new instance of the System.DirectoryServices.DirectorySearcher // class with the specified search root and search filter. // // Parameters: // searchRoot: // The node in the Active Directory Domain Services hierarchy where the search starts. // The System.DirectoryServices.DirectorySearcher.SearchRoot property is initialized // to this value. // // filter: // The search filter string in Lightweight Directory Access Protocol (LDAP) format. // The System.DirectoryServices.DirectorySearcher.Filter property is initialized // to this value. public DirectorySearcher(DirectoryEntry searchRoot, string filter) { //TODO: ALACHISOFT throw new NotImplementedException(); }
public List <ADUser> SearchAD(String FirstName, String LastName, Boolean ForUser, int AuditUserID) { List <ADUser> lstUsers = new List <ADUser>(); String Domain = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADDomain").FirstOrDefault().ParamValue; Parameter adminName = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADUsername").FirstOrDefault(); Parameter password = db.Parameters.AsNoTracking().Where(p => p.ParamName == "ADPassword").FirstOrDefault(); password.ParamValue = util.Decrypt(password.ParamValue); string strRootForest = "LDAP://" + Domain; System.DirectoryServices.DirectoryEntry root = new System.DirectoryServices.DirectoryEntry(strRootForest, adminName.ParamValue, password.ParamValue); System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(root); searcher.SearchScope = SearchScope.Subtree; searcher.ReferralChasing = ReferralChasingOption.All; string vbSearchCriteria = null; if (!(string.IsNullOrEmpty(FirstName))) { vbSearchCriteria = vbSearchCriteria + "(givenName=" + FirstName.TrimStart().TrimEnd() + "*)"; } if (!(string.IsNullOrEmpty(LastName))) { vbSearchCriteria = vbSearchCriteria + "(sn=" + LastName.TrimStart().TrimEnd() + "*)"; } searcher.Filter = "(&(objectClass=user)" + vbSearchCriteria + ")"; SearchResultCollection vbResults = searcher.FindAll(); int vbCount = vbResults.Count; if (vbCount == 0) { throw new Exception("Account cannot be found in Active Directory."); } for (int i = 0; i <= vbCount - 1; i++) { SearchResult result = vbResults[i]; System.DirectoryServices.DirectoryEntry ADsObject = result.GetDirectoryEntry(); string vbUsername = Domain + "\\" + result.Properties["sAMAccountName"][0].ToString(); string vbFname = ""; string vbLname = ""; string vbEmail = ""; string vbEmpNum = ""; string vbManagerPath = ""; Guid vbManagerGUID; int? vbManagerID = null; if (result.Properties["givenName"].Count > 0) { vbFname = result.Properties["givenName"][0].ToString(); } if (result.Properties["sn"].Count > 0) { vbLname = result.Properties["sn"][0].ToString(); } if (result.Properties["mail"].Count > 0) { vbEmail = result.Properties["mail"][0].ToString(); } if (result.Properties["employeeNumber"].Count > 0) { vbEmpNum = result.Properties["employeeNumber"][0].ToString(); } if (result.Properties["manager"].Count > 0) { vbManagerPath = result.Properties["manager"][0].ToString(); vbManagerGUID = GetUserByPath(vbManagerPath).Guid; AddMissingManagers(vbManagerPath, AuditUserID); Employee manager = db.Employees.Where(e => e.ADGUID == vbManagerGUID).FirstOrDefault(); vbManagerID = manager.EmpID; } Boolean isAManger = IsAManager(result.Properties["distinguishedName"][0].ToString(), adminName.ParamValue, password.ParamValue, Domain); ADUser user = new ADUser(); user.Username = vbUsername.Replace(Domain + "\\", ""); user.FirstName = vbFname; user.LastName = vbLname; user.Email = vbEmail; user.ADGUID = ADsObject.Guid.ToString(); user.ManagerID = vbManagerID; user.EmpNum = vbEmpNum; user.IsManager = isAManger; user.ManagerPath = vbManagerPath; lstUsers.Add(user); } for (int i = 0; i <= lstUsers.Count - 1; i++) { string username = lstUsers[i].Username.Replace(Domain + "\\", "").ToString().ToUpper().TrimEnd(); if (ForUser == true) { List <User> lstExistingUsers = db.Users.ToList(); if (lstExistingUsers.Any(s => s.Username.ToString().ToUpper().TrimEnd() == username)) { lstUsers[i].Exists = true; } else { lstUsers[i].Exists = false; } } else { List <Employee> lstExistingEmps = db.Employees.ToList(); if (lstExistingEmps.Any(s => s.Username.ToString().ToUpper().TrimEnd() == username)) { lstUsers[i].Exists = true; } else { lstUsers[i].Exists = false; } } } return(lstUsers); }
public string Authentication(string username, string password) { string DomainAndUsername = ""; string strCommu; bool flgLogin = false; strCommu = ("LDAP://" + (config.Ldap.server)); DomainAndUsername = (config.Ldap.shortDomainName + ("\\" + username)); DirectoryEntry entry = new DirectoryEntry(strCommu, DomainAndUsername, password); object obj; // SearchResultCollection result; SearchResult res; if (entry.Properties.Values.Count == 0) { flgLogin = false; return("username of password incorrect"); } obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); UserInformationModel response = new UserInformationModel(); try { search.Filter = ("(SAMAccountName=" + (username + ")")); search.PropertiesToLoad.Add("cn"); search.PropertiesToLoad.Add("employeeID"); res = search.FindOne(); if ((res == null)) { flgLogin = false; return("Please check user / password"); } else { flgLogin = true; } } catch (Exception ex) { flgLogin = false; return(ex.Message.ToString() + "Please check user / password"); } if ((flgLogin == true)) { StringBuilder sb = new StringBuilder(); res = search.FindOne(); DirectoryEntry de = res.GetDirectoryEntry(); /* * cn => CustomerName * sn => SurName * title => Department * EmployeeID */ response.EmployeeCode = de.Properties["employeeID"].Value != null ? de.Properties["employeeID"].Value.ToString() : ""; response.EmployeeName = username; response.Token = TokenGenerator.GenerateToken(username); response.Username = username; return(JsonConvert.SerializeObject(response)); //return "OK"; } else { strErrMsg = "Password In correct"; } return(strErrMsg); }
/// <summary> /// 创建网站或虚拟目录 /// </summary> /// <param name="WebSite">服务器站点名称(localhost)</param> /// <param name="VDirName">虚拟目录名称</param> /// <param name="Path">实际路径</param> /// <param name="RootDir">true=网站;false=虚拟目錄</param> /// <param name="iAuth">设置目录的安全性,0不允许匿名访问,1为允许,2基本身份验证,3允许匿名+基本身份验证,4整合Windows驗證,5允许匿名+整合Windows验证...更多请查阅MSDN</param> /// <param name="webSiteNum">1</param> /// <param name="serverName">一般為localhost</param> /// <returns></returns> public static bool CreateWebSite(string WebSite, string VDirName, string Path, bool RootDir, int iAuth, int webSiteNum, string serverName, string Sub_VDirName = "") { VDirName = string.IsNullOrEmpty(VDirName) ? "saas" : VDirName; System.DirectoryServices.DirectoryEntry IISSchema; System.DirectoryServices.DirectoryEntry IISAdmin; System.DirectoryServices.DirectoryEntry VDir; try { bool IISUnderNT; // // 确定IIS版本 // IISSchema = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/Schema/AppIsolated"); if (IISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN") { IISUnderNT = true; } else { IISUnderNT = false; } IISSchema.Dispose(); // // Get the admin object // 获得管理权限 // IISAdmin = new System.DirectoryServices.DirectoryEntry("IIS://" + serverName + "/W3SVC/" + webSiteNum + "/Root"); // // If we're not creating a root directory // 如果我们不能创建一个根目录 // if (!RootDir) { // // If the virtual directory already exists then delete it // 如果虚拟目录已经存在则删除 // foreach (System.DirectoryServices.DirectoryEntry v in IISAdmin.Children) { if (v.Name == VDirName) { if (!string.IsNullOrEmpty(Sub_VDirName)) { foreach (System.DirectoryServices.DirectoryEntry sub_v in v.Children) { if (sub_v.Name == Sub_VDirName) { return(false); } } VDir = v.Children.Add(Sub_VDirName, "IIsWebVirtualDir"); CreateVDir(VDir, Sub_VDirName, IISUnderNT, Path, iAuth); return(true); } return(false); // Delete the specified virtual directory if it already exists //try //{ // IISAdmin.Invoke("Delete", new string[] { v.SchemaClassName, VDirName }); // IISAdmin.CommitChanges(); //} //catch (Exception) //{ //} } } } if (!RootDir) { VDir = IISAdmin.Children.Add(VDirName, "IIsWebVirtualDir"); } else { VDir = IISAdmin; } CreateVDir(VDir, VDirName, IISUnderNT, Path, iAuth); return(true); // // Create the virtual directory // 创建一个虚拟目录 // // // Make it a web application // 创建一个web应用 // if (IISUnderNT) { VDir.Invoke("AppCreate", false); } else { VDir.Invoke("AppCreate", true); } // // Setup the VDir // 安装虚拟目录 //AppFriendlyName,propertyName,, bool chkRead,bool chkWrite, bool chkExecute, bool chkScript,, true, false, false, true VDir.Properties["AppFriendlyName"][0] = VDirName; //应用程序名称 VDir.Properties["AccessRead"][0] = true; //设置读取权限 VDir.Properties["AccessExecute"][0] = false; VDir.Properties["AccessWrite"][0] = false; VDir.Properties["AccessScript"][0] = true; //执行权限[纯脚本] //VDir.Properties["AuthNTLM"][0] = chkAuth; VDir.Properties["EnableDefaultDoc"][0] = true; VDir.Properties["EnableDirBrowsing"][0] = false; VDir.Properties["DefaultDoc"][0] = "Default.aspx,Index.aspx,Index.asp"; //设置默认文档,多值情况下中间用逗号分割 VDir.Properties["Path"][0] = Path; VDir.Properties["AuthFlags"][0] = iAuth; // // NT doesn't support this property // NT格式不支持这特性 // if (!IISUnderNT) { VDir.Properties["AspEnableParentPaths"][0] = true; } VDir.CommitChanges(); return(true); } catch (Exception ex) { return(false); } }
public void AddMissingManagers(String ManagerPath, int AuditUserID) { List <System.DirectoryServices.DirectoryEntry> mgrsToAdd = new List <System.DirectoryServices.DirectoryEntry>(); String mgrToAdd = ""; System.DirectoryServices.DirectoryEntry mgrAD = GetUserByPath(ManagerPath); Employee manager = db.Employees.Where(e => e.ADGUID == mgrAD.Guid).FirstOrDefault(); if (manager == null) { mgrToAdd = mgrAD.Path; if (!mgrsToAdd.Contains(mgrAD)) { mgrsToAdd.Add(mgrAD); } while (mgrToAdd != "") { if (mgrAD.Properties["manager"].Count > 0) { String nextMgrPath = mgrAD.Properties["manager"][0].ToString(); mgrAD = GetUserByPath(nextMgrPath); manager = db.Employees.Where(e => e.ADGUID == mgrAD.Guid).FirstOrDefault(); if (manager == null) { mgrToAdd = mgrAD.Path; if (!mgrsToAdd.Contains(mgrAD)) { mgrsToAdd.Add(mgrAD); } } else { mgrToAdd = ""; } } else { mgrToAdd = ""; } } for (int i = mgrsToAdd.Count(); i-- > 0;) { System.DirectoryServices.DirectoryEntry m = mgrsToAdd[i]; if (m.Properties["manager"].Count > 0) { Guid thisMgrGUID = GetUserByPath(m.Properties["manager"][0].ToString()).Guid; manager = db.Employees.Where(e => e.ADGUID == thisMgrGUID).FirstOrDefault(); } else { manager = null; } AddEmployee(m.Guid.ToString(), m.Properties["mail"].Count > 0 ? m.Properties["mail"][0].ToString() : "", m.Properties["givenName"].Count > 0 ? m.Properties["givenName"][0].ToString() : "", m.Properties["sn"].Count > 0 ? m.Properties["sn"][0].ToString() : "", m.Properties["sAMAccountName"][0].ToString(), "true", manager != null ? manager.EmpID.ToString() : "", m.Properties["employeeNumber"].Count > 0 ? m.Properties["employeeNumber"][0].ToString() : "", AuditUserID); } } }
//---------------------------------------------------- //Done on The Run, Must Be Validated! public static adUsers locateUsr(PrincipalContext context, string adUser) { adUsers ladUser = new adUsers(); try { if (context.ContextType.ToString().ToLower().Contains("domain")) { UserPrincipal usr = UserPrincipal.FindByIdentity(context, adUser); if (usr != null) { System.DirectoryServices.DirectoryEntry underField = usr.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry; ladUser.DN = usr.DistinguishedName; ladUser.FirstName = usr.GivenName; ladUser.LastName = usr.Surname; ladUser.DisplayName = usr.DisplayName; ladUser.Description = usr.Description; ladUser.LastBadPasswordAttempt = Convert.ToDateTime(usr.LastBadPasswordAttempt); ladUser.LastPasswordChange = Convert.ToDateTime(usr.LastPasswordSet); ladUser.Email = usr.EmailAddress; ladUser.Account = usr.SamAccountName; if (adUser.Substring(0, 2).ToLower().Contains("fe") | adUser.Substring(0, 2).ToLower().Contains("fr") | adUser.Substring(0, 2).ToLower().Contains("fc")) { // ladUser.Photo = dLibLke.usrPhoto(dLibLke.findDv(usr.SamAccountName)); } else { ladUser.Photo = Seeker.Properties.Resources.usrPhoto; } if (underField.Properties.Contains("company")) { ladUser.Company = underField.Properties["company"].Value.ToString(); } if (underField.Properties.Contains("telephoneNumber")) { ladUser.Phone = underField.Properties["telephoneNumber"].Value.ToString(); } if (underField.Properties.Contains("otherTelephone")) { for (int i = 0; i < underField.Properties["otherTelephone"].Count; i++) { ladUser.Phone = ladUser.Phone + " - " + underField.Properties["otherTelephone"][i].ToString(); } } if (underField.Properties.Contains("info")) { ladUser.Notes = underField.Properties["info"].Value.ToString(); } if (underField.Properties.Contains("whenCreated")) { ladUser.CreationDate = underField.Properties["whenCreated"].Value.ToString(); } if (underField.Properties.Contains("whenChanged")) { ladUser.ChangedDate = underField.Properties["whenChanged"].Value.ToString(); } if (IsUserAccountActive(underField)) { ladUser.Status = "Active"; } else { ladUser.Status = "Disabled"; } if (usr.AccountLockoutTime != null) { ladUser.Status = ladUser.Status + ",Locked on: " + usr.AccountLockoutTime.ToString(); } else { ladUser.Status = ladUser.Status + ", Unlocked"; } if (underField.Properties.Contains("serialNumber")) { StringBuilder userSerials = new StringBuilder(); if (underField.Properties["serialNumber"].Count > 1) { foreach (string s in underField.Properties["serialNumber"]) { userSerials.Append(s + ","); } ladUser.SerialNumber = userSerials.ToString(); } else { if (underField.Properties["serialNumber"].Count == 1) { DateTime date; string[] formats = { "dd/MM/yyyy hh:mm:ss", "dd/MM/yyyy" }; if (DateTime.TryParseExact(underField.Properties["serialNumber"].Value.ToString(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { ladUser.SerialNumber = date.ToString(); } else { ladUser.SerialNumber = null; } } else { ladUser.SerialNumber = null; } } } else { ladUser.SerialNumber = null; } if (underField.Properties.Contains("department")) { ladUser.Division = underField.Properties["department"].Value.ToString(); } else { ladUser.Division = "Unknown"; } if (underField.Properties.Contains("l")) { ladUser.Location = underField.Properties["l"].Value.ToString(); } if (underField.Properties.Contains("physicalDeliveryOfficeName")) { ladUser.Location = ladUser.Location + " - " + underField.Properties["physicalDeliveryOfficeName"].Value.ToString(); } } else { return(null); } } else { UserPrincipal usr = UserPrincipal.FindByIdentity(context, adUser); if (usr != null) { ladUser.DN = usr.SamAccountName; ladUser.FirstName = usr.GivenName; ladUser.LastName = usr.Surname; ladUser.DisplayName = usr.DisplayName; ladUser.Description = usr.Description; ladUser.Email = usr.EmailAddress; ladUser.Account = usr.SamAccountName; } else { return(null); } } } catch (Exception ex) { MessageBox.Show("adUsrDetailsFinder \n\n" + "\n\nObject: " + adUser + "\n\nMessage: " + ex.Message + "\n\nSource: " + ex.Source + "\n\nStack: " + ex.StackTrace + "\n\nTarget: " + ex.TargetSite, "Information: Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { } return(ladUser); }
public string validarUsuario(string usuario, string clave, string dominio) { dominio = (dominio == "") ? "GRUPORANSA" : dominio; string rpta = ""; AccesoUsuarioOutput usuarios = new AccesoUsuarioOutput(); DirectoryEntry domain = new DirectoryEntry("LDAP://" + dominio); using (DirectorySearcher Searcher = new DirectorySearcher(dominio)) { //Searcher.Filter = "(&(objectCategory=user)(ANR=" + usuario + " * ))"; // busca todas las cuentas que se parezcan Searcher.Filter = "(SAMAccountName=" + usuario + ")"; // "(SAMAccountName=" & usuario & ")"; // filtra por usuario especifico Searcher.SearchScope = SearchScope.Subtree; // Start at the top and keep drilling down Searcher.PropertiesToLoad.Add("sAMAccountName"); // Load User ID Searcher.PropertiesToLoad.Add("displayName"); // Load Display Name Searcher.PropertiesToLoad.Add("givenName"); // Load Users first name Searcher.PropertiesToLoad.Add("sn"); // Load Users last name Searcher.PropertiesToLoad.Add("distinguishedName"); // Users Distinguished name Searcher.PropertiesToLoad.Add("proxyAddresses"); // correo del usuario Searcher.PropertiesToLoad.Add("department"); // area de trabajo Searcher.PropertiesToLoad.Add("title"); // rol del usuario Searcher.PropertiesToLoad.Add("userAccountControl"); // Users Distinguished name Searcher.Sort.PropertyName = "sAMAccountName"; // Sort by user ID Searcher.Sort.Direction = System.DirectoryServices.SortDirection.Ascending; // A-Zt) using (var users = Searcher.FindAll()) // Users contains our searh results { if (users.Count > 0) { foreach (SearchResult User in users) // goes throug each user in the search resultsg { variablesGlobales._estCuentaUsuario = Convert.ToInt32(User.Properties["userAccountControl"][0]); int flagExists = variablesGlobales._estCuentaUsuario & 0x2; if (flagExists > 0) { usuarios.IDUSER = 0; usuarios.USERNM = "La cuenta de usuario se encuentra deshabilitada"; usuarios.NVLACC = "SIN ACCESO"; usuarios.PERMISOS = new List <CE_AccesosUsuario>(); rpta = JsonConvert.SerializeObject(usuarios); } System.DirectoryServices.DirectoryEntry Entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dominio, usuario, clave); System.DirectoryServices.DirectorySearcher valSearcher = new System.DirectoryServices.DirectorySearcher(Entry); valSearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel; try { System.DirectoryServices.SearchResult Results = valSearcher.FindOne(); } catch (Exception ex) { //rpta = "[{id=0, mensaje = '"+ ex.Message + "'}]"; rpta = "{\"id\":0, \"mensaje\": \"" + ex.Message + "\"}"; return(rpta); } if (User.Properties.Contains("displayName")) { variablesGlobales._NombreUsuario = System.Convert.ToString(User.Properties["displayName"][0]); } variablesGlobales._rolUsuario = (User.Properties["title"].Count > 0) ? System.Convert.ToString(User.Properties["title"][0]) : ""; variablesGlobales._dptoUsuario = (User.Properties["department"].Count > 0) ? System.Convert.ToString(User.Properties["department"][0]) : ""; variablesGlobales._correoUsuario = (User.Properties["proxyAddresses"].Count > 0) ? System.Convert.ToString(User.Properties["proxyAddresses"][0]) : ""; variablesGlobales._cuentaUsuario = (User.Properties["sAMAccountName"].Count > 0) ? System.Convert.ToString(User.Properties["sAMAccountName"][0]).ToUpper() : ""; usuarios = ValidarAccesos(variablesGlobales._cuentaUsuario); rpta = JsonConvert.SerializeObject(usuarios); } } else { usuarios.IDUSER = 0; usuarios.USERNM = "No EXiste"; usuarios.NVLACC = "SIN ACCESO"; usuarios.PERMISOS = new List <CE_AccesosUsuario>(); rpta = JsonConvert.SerializeObject(usuarios); } } } return(rpta); }
public LdapUser GetAuthenticatedLdapUser(string userName, string password) { //string domain = ConfigurationManager.AppSettings["DomainName"].ToString(); string domain = "exalca"; string domainAndUsername = string.Empty; string SAMAccountName = string.Empty; if (userName.Contains(@"\")) { domainAndUsername = userName; SAMAccountName = Regex.Split(domainAndUsername, @"\")[1]; } else { domainAndUsername = domain + @"\" + userName; SAMAccountName = userName; } //var _path = ConfigurationManager.AppSettings["LDAPConnectionString"].ToString(); var _path = "LDAP://exalca.corp"; System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(_path, domainAndUsername, password); System.DirectoryServices.DirectoryEntry dirEntry = new System.DirectoryServices.DirectoryEntry(); LdapUser user = new LdapUser(); try { // Bind to the native AdsObject to force authentication. Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(&(objectClass=user)(SAMAccountName=" + SAMAccountName + "))"; SearchResult result = search.FindOne(); if (result == null) { return(null); } else { dirEntry = result.GetDirectoryEntry(); user.UserID = dirEntry.Guid; user.Path = result.Path; user.Email = GetProperty(result, "mail"); user.UserName = GetProperty(result, "samaccountname"); user.DisplayName = GetProperty(result, "displayname"); user.FirstName = GetProperty(result, "givenName"); user.LastName = GetProperty(result, "sn"); user.Mobile = GetProperty(result, "mobile"); } } catch (Exception ex) { ErrorLog.WriteToFile("AuthorizationServerProvider/GetAuthenticatedLdapUser :- ", ex); return(null); } finally { entry.Dispose(); dirEntry.Dispose(); } return(user); }
/// <summary> /// 查询制定用户是否是锁定状态 /// </summary> /// <param name="de"></param> /// <returns></returns> public static bool IsAccountLockOut(DirectoryEntry de) { return(Convert.ToBoolean(de.InvokeGet("IsAccountlocked"))); }