/// <summary> /// Search a user hierarchicaly in the AD structure /// </summary> /// <param name="userName">The user name or identifier</param> /// <param name="ac">The principal context global configuration</param> /// <param name="pc">The principal context this user was found in</param> /// <returns></returns> private static UserPrincipal SearchUser(string userName, AccountManagementPrincipalContext ac, out PrincipalContext pc) { UserPrincipal user = null; var name = new FqdnNameParser(userName); if (name.ContextType == ContextType.Machine) { pc = BuildPrincipal(null); user = FindUser(userName, pc); if (user != null) { return(user); } pc.Dispose(); return(null); } // Probar sin OU pc = BuildPrincipal(ac); user = FindUser(userName, pc); if (user != null) { return(user); } pc.Dispose(); // Probar con OU pc = BuildPrincipalWithoutOu(ac); user = FindUser(userName, pc); if (user != null) { return(user); } pc.Dispose(); return(null); }
public ActionResult GetListSearch(string name) { //string strDomain = "192.168.0.1"; string strUserName = "******"; string strPassword = "******"; string strDomain = "domaina.int.net"; string strUserName = "******"; string strPassword = "******"; PrincipalContext ctx = new PrincipalContext(ContextType.Domain, strDomain); List <USER> _lstUser = new List <USER>(); try { bool bValid = ctx.ValidateCredentials(strUserName, strPassword, ContextOptions.Negotiate); // Additional check to search user in directory. if (bValid) { //| OU=Friesland Foods Dutch Lady Malaysia OU=Friesland Foods Dutch Lady Vietnam, string container = @"OU=Friesland Foods Dutch Lady Malaysia,DC=domaina,DC=int,DC=net"; //string container = "OU=IVGHN,DC=ivg,DC=vn"; _lstUser = getOU(container, name, "Friesland Foods Dutch Lady Malaysia"); string container1 = @"OU=Friesland Foods Dutch Lady VietNam,DC=domaina,DC=int,DC=net"; _lstUser.AddRange(getOU(container1, name, "Friesland Foods Dutch Lady VietNam")); } } catch (Exception ex) { throw new AuthenticationException("Authentication Error in PrincipalContext. Message: " + ex.Message); } finally { ctx.Dispose(); } return(PartialView("_ListUserTableDomain", _lstUser.ToList())); }
public bool checkUser(string Domain, string username, string pwd) { string sDomain = "LDAP://172.22.14.40/"; string sDefaultOU = "ou=users,ou=system"; string sServiceUser = @"uid=admin,ou=system"; string sServicePassword = "******"; PrincipalContext oPrincipalContext = new PrincipalContext (ContextType.Domain, sDomain, sDefaultOU, sServiceUser, sServicePassword); UserPrincipal usr = UserPrincipal.FindByIdentity(oPrincipalContext, IdentityType.SamAccountName, "pnunez"); if (usr != null) { if (usr.Enabled == false) { usr.Enabled = true; } usr.Save(); usr.Dispose(); } oPrincipalContext.Dispose(); return(true); }
public List <String> QueryADGroupMembers(String sGroup) { List <String> ListADGroupMembers = new List <String>(); try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain); GroupPrincipal grpObj = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, sGroup); if (grpObj != null) { foreach (Principal p in grpObj.GetMembers(true)) { String sObjName = p.SamAccountName.ToString().Trim(); if (sObjName.Substring(sObjName.Length - 1, 1) == "$") { sObjName = sObjName.Substring(0, sObjName.Length - 1); } ListADGroupMembers.Add(sObjName); } grpObj.Dispose(); ctx.Dispose(); } return(ListADGroupMembers); } catch (Exception ex) { WriteBuffer("Error source: QueryADGroupMembers()" + " " + ex.Message); return(ListADGroupMembers); } }
public void ADGetUsersInGroup(string strGroup, List <string> listUserNames) { try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, this.Domain); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, strGroup); if (grp != null) { foreach (Principal p in grp.GetMembers(true)) { listUserNames.Add(p.SamAccountName); } grp.Dispose(); ctx.Dispose(); } else { MessageBox.Show("The group [" + strGroup + "] was not found in the Active Direcotry.", "ADGetUsersInGroup(): Error Connecting to Active Directory"); } } catch (System.Exception x) { Jrfc.Exception.HandleException(x); } }
public static bool AddUserToGroup(string samAccountName, string groupName, AdAdminConfig config) { if (IfUserExist(samAccountName, config)) { if (!IfUserExistInGroup(samAccountName, groupName, config)) { try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, config.ServerIpOrDomain, config.AdminAccount, config.AdminPwd); // find the group in question GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, samAccountName); group.Members.Add(user); group.Save(); group.Dispose(); user.Dispose(); ctx.Dispose(); } catch (Exception ex) { return(false); } return(true); } return(false); } return(false); }
public static List <string> GetADSecurityGroupUsers(String sgAlias) { List <string> userList = new List <string>(); using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, sgAlias); if (grp != null) { foreach (Principal p in grp.GetMembers(true)) { userList.Add(p.SamAccountName); Console.WriteLine(p.SamAccountName); } grp.Dispose(); ctx.Dispose(); } else { Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?"); } } return(userList); }
public string[] GetLDAPUserInformationByCommonName(string commonName) { Ldap ldap = Ldap.Instance; PrincipalContext ctx = ldap.GetPrincipalContext; userPrincipal = new UserPrincipal(ctx); searchUser = new PrincipalSearcher(); try { if (commonName != "" && commonName.Length != 0) { userPrincipal.EmailAddress = $"{commonName}@zbc.dk"; searchUser.QueryFilter = userPrincipal; userPrincipal = (UserPrincipal)searchUser.FindOne(); userInfo[0] = userPrincipal.GivenName; userInfo[1] = userPrincipal.Surname; } } catch (Exception ex) { Debug.WriteLine($"Exception: {ex.Message}"); userInfo[0] = "User not found."; return(userInfo); } finally { ctx.Dispose(); } return(userInfo); }
public bool Isvalid(string Username, string Password) { PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, VulindlelaFTPServer.Properties.Settings.Default.VulIP, "CN=" + Username + ",OU=USERS,OU=Vulindlela3," + VulindlelaFTPServer.Properties.Settings.Default.VulDC, VulindlelaFTPServer.Properties.Settings.Default.VulMasterUser, VulindlelaFTPServer.Properties.Settings.Default.VulMasterPassword); bool result; try { UserPrincipal.FindByIdentity(principalContext, Username); result = true; } catch (Exception) { result = false; } finally { principalContext.Dispose(); } return(result); }
public static void getMembers(string group) { List <PrincipalSearchResult <Principal> > list = new List <PrincipalSearchResult <Principal> >(); try { PrincipalContext LocalMachine = new PrincipalContext(ContextType.Machine); GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(LocalMachine, IdentityType.Name, group); if (gPrincipal != null) { foreach (var y in gPrincipal.GetMembers(true)) { System.Console.WriteLine(y); } } foreach (var y in gPrincipal.GetMembers()) { System.Console.WriteLine(y); } LocalMachine.Dispose(); } catch (PrincipalOperationException ex) { System.Console.WriteLine(ex.Message); } }
public void AddUser(UserInfo userInfo) { if (!Exists) { throw new GroupDoesNotExistException(Name); } if (!userInfo.Exists) { throw new UserDoesNotExistException(userInfo.Name); } var context = new PrincipalContext(ContextType.Machine); var group = GroupPrincipal.FindByIdentity(context, Name); var user = UserPrincipal.FindByIdentity(context, userInfo.Name); try { group.Members.Add(user); group.Save(); } finally { context.Dispose(); if (group != null) { group.Dispose(); } if (user != null) { user.Dispose(); } } }
//Unlocks account returns message depending on success?failure public string UnlockAccount(string searchQuery) { string accountUnlockStatus = string.Empty; PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userResult = UserPrincipal.FindByIdentity(context, searchQuery); try { if (userResult != null) { userResult.UnlockAccount(); accountUnlockStatus = "Account was unlocked."; } } catch (PrincipalOperationException pEx) { accountUnlockStatus = pEx.Message; } userResult.Dispose(); context.Dispose(); } return(accountUnlockStatus); }
/// <summary> /// Dispose everything we have. /// </summary> public void Dispose() { if (principalContext != null) { principalContext.Dispose(); } }
//Reset user account password, returns message depending on success?failure public string ResetPassword(string searchQuery, string password) { string passwordStatusMessage = String.Empty; PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userResult = UserPrincipal.FindByIdentity(context, searchQuery); if (userResult != null && userResult.SamAccountName != AppAuth["Username"]) { try { userResult.SetPassword(password); passwordStatusMessage = "Password was successfully changed."; } catch (Exception e) { passwordStatusMessage = e.Message; } userResult.Dispose(); } else { passwordStatusMessage = "The password for this account cannot be reset via this application."; } context.Dispose(); } return(passwordStatusMessage); }
//Retrieve all groups public List <string> GetADGroupsList() { List <string> adGroups = new List <string>(); PrincipalContext context = GetContext(); if (context != null) { GroupPrincipal groups = new GroupPrincipal(context); //searcher to search groups PrincipalSearcher searcher = new PrincipalSearcher(groups); foreach (var found in searcher.FindAll()) { DirectoryEntry deFound = (DirectoryEntry)found.GetUnderlyingObject() as DirectoryEntry; if ((int)deFound.Properties["samAccountType"].Value == 536870912) { Console.WriteLine("Groups is Alias Object (BuiltIn) and will not be aded to list."); } else { adGroups.Add(found.ToString()); } } adGroups.Sort(); groups.Dispose(); searcher.Dispose(); context.Dispose(); } return(adGroups); }
public void Terminate() { if (_domainGroupContext != null) { _domainGroupContext.Dispose(); } }
private void EscalateReturn_Load(object sender, EventArgs e) { string groupName = "Domain Users"; string domainName = "192.168.10.5"; //get AD users PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName); try { foreach (Principal p in grp.GetMembers(false)) { if (p.DisplayName != null) { comboBox1.Items.Add(p.DisplayName); } } grp.Dispose(); ctx.Dispose(); } catch { MessageBox.Show("Server not available. Check internet connection"); } comboBox1.Sorted = true; }
public bool ContainsUser(UserInfo userInfo) { if (!Exists) { throw new GroupDoesNotExistException(Name); } if (!userInfo.Exists) { throw new UserDoesNotExistException(userInfo.Name); } var context = new PrincipalContext(ContextType.Machine); var group = GroupPrincipal.FindByIdentity(context, Name); try { var members = group.Members; return(members.Any(m => m.Name == userInfo.Name)); } finally { context.Dispose(); if (group != null) { group.Dispose(); } } }
//Searches specified OU against AD and finds all enabled user accounts public List <string> GetADUserList(string domain) { List <string> ADActiveUserList = new List <string>(); PrincipalContext context = GetContext(); if (context != null) { UserPrincipal userPrin = new UserPrincipal(context); PrincipalSearcher searcher = new PrincipalSearcher(userPrin); foreach (var result in searcher.FindAll()) { DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; UserPrincipal u = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, de.Properties["samAccountName"].Value.ToString()); if (u.Enabled == true) { if (u.SamAccountName != AppAuth["Username"]) { ADActiveUserList.Add(u.SamAccountName); } } } searcher.Dispose(); userPrin.Dispose(); context.Dispose(); } ADActiveUserList.Sort(); return(ADActiveUserList); }
public void Dispose() { if (context != null) { context.Dispose(); } }
/// <summary> /// Search for a group in diferent principal context in the following order: local, domain without OU, domain with OU /// </summary> /// <param name="groupName"></param> /// <param name="ac"></param> /// <param name="pc"></param> /// <returns></returns> private static GroupPrincipal SearchGroup(string groupName, AccountManagementPrincipalContext ac, out PrincipalContext pc) { var name = new FqdnNameParser(groupName); GroupPrincipal group = null; if (name.ContextType == ContextType.Machine) { pc = BuildPrincipal(null); group = FindGroup(groupName, pc); if (group != null) { return(group); } pc.Dispose(); return(null); } // Look in provided OU pc = BuildPrincipal(ac); group = FindGroup(groupName, pc); if (group != null) { return(group); } pc.Dispose(); // Look in domain pc = BuildPrincipalWithoutOu(ac); group = FindGroup(groupName, pc); if (group != null) { return(group); } pc.Dispose(); return(null); }
/// <summary> /// Provides the domain user full details. /// </summary> /// <param name="domainName">Name of the domain.</param> /// <returns></returns> public static DataSet ProvideDomainUserFullDetails(string domainName, string sessionID, string userSource, string defaultDepartment, string fullNameAttribute) { DataSet UsersList = new DataSet(); UsersList.Tables.Add(); UsersList.Tables[0].Columns.Add("REC_SYSID", typeof(string)); UsersList.Tables[0].Columns.Add("USER_ID", typeof(string)); UsersList.Tables[0].Columns.Add("SESSION_ID", typeof(string)); UsersList.Tables[0].Columns.Add("USR_SOURCE", typeof(string)); UsersList.Tables[0].Columns.Add("USR_ROLE", typeof(string)); UsersList.Tables[0].Columns.Add("DOMAIN", typeof(string)); UsersList.Tables[0].Columns.Add("FIRST_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("LAST_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("EMAIL", typeof(string)); UsersList.Tables[0].Columns.Add("RESIDENCE_ADDRESS", typeof(string)); UsersList.Tables[0].Columns.Add("COMPANY", typeof(string)); UsersList.Tables[0].Columns.Add("STATE", typeof(string)); UsersList.Tables[0].Columns.Add("COUNTRY", typeof(string)); UsersList.Tables[0].Columns.Add("PHONE", typeof(string)); UsersList.Tables[0].Columns.Add("EXTENSION", typeof(string)); UsersList.Tables[0].Columns.Add("FAX", typeof(string)); UsersList.Tables[0].Columns.Add("DEPARTMENT", typeof(string)); UsersList.Tables[0].Columns.Add("USER_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("CN", typeof(string)); UsersList.Tables[0].Columns.Add("DISPLAY_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("FULL_NAME", typeof(string)); UsersList.Tables[0].Columns.Add("C_DATE", typeof(string)); UsersList.Tables[0].Columns.Add("REC_ACTIVE", typeof(string)); UsersList.Tables[0].Columns.Add("AD_PIN", typeof(string)); UsersList.Tables[0].Columns.Add("AD_CARD", typeof(string)); string cardValue = ""; string pinValue = ""; int valuesCount = 0; PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Constants.DOMAIN_USERS); if (group != null) { foreach (Principal principal in group.GetMembers(false)) { string userName = principal.SamAccountName; string department = ""; if (string.IsNullOrEmpty(department)) { department = defaultDepartment; } UsersList.Tables[0].Rows.Add(valuesCount, principal.SamAccountName, sessionID, userSource, "User", domainName, principal.Name, "", principal.UserPrincipalName, "", "", "", "", "", "", "", department, userName, "", principal.DisplayName, principal.SamAccountName, DateTime.Now.ToString(), "True", pinValue, cardValue); valuesCount++; } group.Dispose(); context.Dispose(); } return(UsersList); }
/// <summary> /// Validates the username and password of a given user /// </summary> /// <param name="sUserName">The username to validate</param> /// <param name="sPassword">The password of the username to validate</param> /// <returns>Returns True of user is valid</returns> public bool ValidateCredentials(string sUserName, string sPassword) { PrincipalContext oPrincipalContext = GetPrincipalContext(); bool flag = oPrincipalContext.ValidateCredentials(sUserName, sPassword); oPrincipalContext.Dispose(); return(flag); }
public void Dispose() { if (m_context != null) { m_context.Dispose(); m_context = null; } }
public void UserName_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws <ObjectDisposedException>(() => context.UserName); }
public void ConnectedServer_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws <ObjectDisposedException>(() => context.ConnectedServer); }
public void ValidateCredentials_Disposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws <ObjectDisposedException>(() => context.ValidateCredentials(null, null)); Assert.Throws <ObjectDisposedException>(() => context.ValidateCredentials(null, null, ContextOptions.Negotiate)); }
public static bool ValidateUser(string userName, string password) { PrincipalContext pc = new PrincipalContext(ContextType.Domain, "kfnl.gov.sa"); // validate the credentials bool isValid = pc.ValidateCredentials(userName, password); pc.Dispose(); return(isValid); }
private IdentityUser AuthenticateUsingPrincipalcontext(string strDomain, string strUserName, string strPassword) { IdentityUser _Identity = new IdentityUser(); var ck = db.USERS.Where(m => m.Username.Equals(strUserName)).Count(); if (ck > 0) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, strDomain); try { bool bValid = ctx.ValidateCredentials(strUserName, strPassword, ContextOptions.Negotiate); // Additional check to search user in directory. if (bValid) { var ctx1 = new PrincipalContext(ContextType.Domain, strDomain, strUserName, strPassword); UserPrincipal prUsr = new UserPrincipal(ctx1); prUsr.SamAccountName = strUserName; PrincipalSearcher srchUser = new PrincipalSearcher(prUsr); UserPrincipal foundUser = srchUser.FindOne() as UserPrincipal; if (foundUser != null) { _Identity = new IdentityUser(); var u = db.USERS.Where(m => m.Username.Equals(foundUser.SamAccountName)).SingleOrDefault(); if (u != null) { _Identity.UserId = u.User_Id; _Identity.UserName = foundUser.SamAccountName; _Identity.FullName = foundUser.Name; _Identity.Address = foundUser.EmailAddress; _Identity.Email = foundUser.EmailAddress; } } else { throw new AuthenticationException("Please enter valid UserName/Password."); } } else { throw new AuthenticationException("Please enter valid UserName/Password."); } } catch (Exception ex) { throw new AuthenticationException("Authentication Error in PrincipalContext. Message: " + ex.Message); } finally { ctx.Dispose(); } } return(_Identity); }
private void RefreshContext() { string username = "******"; string password = "******"; //TODO: don't assume it exists, create it if its not string OU = "Tests"; string baseDomain = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split(new char[] { '\\' })[1] + "-TEST"; string domain = String.Format("{0}.nttest.microsoft.com", baseDomain); string container = String.Format("ou={0},dc={1},dc=nttest,dc=microsoft,dc=com", OU, baseDomain); if (domainContext != null) { domainContext.Dispose(); } domainContext = new PrincipalContext(ContextType.Domain, domain, container, username, password); }