public ActionResult _LoggedInAs() { User user = new User(); try { AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal principal = (WindowsPrincipal) Thread.CurrentPrincipal; //String adDomainUserName = principal.Identity.Name; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) { UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name); user.FirstName = up.GivenName; user.LastName = up.Surname; user.Email = up.EmailAddress; user.UserName = (principal.Identity.Name).Split('\\')[1]; } /* if (adDomainUserName != null) { string adUserName = adDomainUserName.Split('\\')[1]; user = _ldapService.GetUserByUserName(adUserName); }*/ } catch (Exception e) { logger.Error("Exception", e); } Session["user"] = user; return View(user); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (base.AuthorizeCore(httpContext)) { /* Return true immediately if the authorization is not locked down to any particular AD group */ if (String.IsNullOrEmpty(Groups)) { return true; } string DomainName = ConfigurationManager.AppSettings["Domain"].ToString(); if (string.IsNullOrEmpty(DomainName)) { throw new ArgumentException("Domain missing from AppSettings!"); } // Get the AD groups var groups = Groups.Split(',').ToList(); // Verify that the user is in the given AD group (if any) var context = new PrincipalContext(ContextType.Domain,DomainName); var userPrincipal = UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,httpContext.User.Identity.Name); foreach (var group in groups) { if (userPrincipal.IsMemberOf(context, IdentityType.Name, group)) { return true; } } } return false; }
public static bool UserInGroup(IPrincipal user, params AdGroup[] groups) { using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { var context = new PrincipalContext(ContextType.Domain); var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, user.Identity.Name); if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(AdGroup.SuperAdmin))) { return true; } //Если юзер Суперадмин if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(AdGroup.SpeCalcKontroler))) { return true; } //Если юзер Контролер foreach (var grp in groups) { if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp))) { return true; } } return false; } }
public static void createUsers(string domain, string ou, int numOfUsers) { ContextType contextType = ContextType.Domain; using (PrincipalContext ctx = new PrincipalContext(contextType, domain, ou)) { for(int i=0; i<numOfUsers; i++) { try { UserPrincipal userPrincipal = new UserPrincipal(ctx); userPrincipal.Surname = SampleData.GetSampleValueRandom(SampleData.LastNames); userPrincipal.GivenName = SampleData.GetSampleValueRandom(SampleData.FirstNames); ; userPrincipal.SamAccountName = userPrincipal.GivenName.ToLower() + "." + userPrincipal.Surname.ToLower(); userPrincipal.Name = userPrincipal.GivenName + " " + userPrincipal.Surname; userPrincipal.DisplayName = userPrincipal.GivenName + " " + userPrincipal.Surname; string pwdOfNewlyCreatedUser = "******"; userPrincipal.SetPassword(pwdOfNewlyCreatedUser); userPrincipal.Enabled = true; userPrincipal.PasswordNeverExpires = true; userPrincipal.Save(); } catch (Exception ex) { Errors.Log(ex); } } } }
private void button1_Click(object sender, EventArgs e) { if (this.txtUserName.Text.Length < 1) { MessageBox.Show("Please Enter User Name"); return; } if (this.txtPassword.Text.Length < 1) { MessageBox.Show("Please Enter Password"); return; } PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "COS"); principalContext.ValidateCredentials(this.txtUserName.Text, this.txtPassword.Text); try { if (!principalContext.ValidateCredentials(this.txtUserName.Text, this.txtPassword.Text)) { this.txtPassword.Text = string.Empty; MessageBox.Show("User Name or Password Not correct"); } else { (new frmMain()).Show(); base.Hide(); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } }
private void treeViewGroup_AfterSelect(object sender, TreeViewEventArgs e) { try { //Start of: Change Font of selected node if (prevNode != null) { prevNode.ForeColor = Color.Black; prevNode.NodeFont = new Font(Font.FontFamily, Font.Size, FontStyle.Regular); } prevNode = treeViewGroup.SelectedNode; treeViewGroup.SelectedNode.ForeColor = Color.Blue; treeViewGroup.SelectedNode.NodeFont = new Font(Font.FontFamily.Name, Font.Size, FontStyle.Regular); //End of: Change Font of selected node PrincipalContext ctx = new PrincipalContext(ContextType.Domain, treeViewGroup.SelectedNode.ImageKey); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, treeViewGroup.SelectedNode.Text); userDetails = (from u in grp.Members select new UserDetails { DisplayName = u.DisplayName, UserName = u.SamAccountName,Domain = u.Context.Name }).OrderBy(x => x.DisplayName).ToList(); userControlListing.DataSource = userDetails; } catch (Exception) { throw; } }
// Implement the overloaded search method FindByIdentity. public static new ExtendedUserPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (ExtendedUserPrincipal)FindByIdentityWithType(context, typeof(ExtendedUserPrincipal), identityValue); }
private static void SearchComp(List<CompData> comps, string domainName) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName)) { foreach (var comp in comps) { if (comp.CompName == null) { var sp = new ComputerPrincipal(ctx); sp.Description = comp.User.Name; var searcher = new PrincipalSearcher(sp); var res = searcher.FindAll(); foreach (var p in res) { if (p is ComputerPrincipal) { var findComp = (ComputerPrincipal)p; comp.CompName = findComp.Name; comp.CompPath = findComp.DistinguishedName; } } } } } }
public bool validateUser(string username, string password) { string UN = username; string PW = password; bool state; bool inGrp = false; PrincipalContext Context = new PrincipalContext(ContextType.Domain, "wallworkinc.com"); GroupPrincipal group = GroupPrincipal.FindByIdentity(Context, "Help Desk Admins"); state = Context.ValidateCredentials(UN, PW); if (state != false) { foreach (Principal principal in group.Members) { string name = principal.SamAccountName; if (name == UN) { inGrp = true; } } } else { inGrp = false; } return inGrp; }
private void buttonGetUsers_Click(object sender, EventArgs e) { _users = loadUsersFromTxt(); if (_users.Count == 0) { string domainName = textBoxDomain.Text; using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, textBoxGroup.Text); if (group != null) { HashSet<UserData> usersHash = new HashSet<UserData>(); IterateGroup(group, usersHash); _users = usersHash.ToList(); } else { MessageBox.Show("Группа не найдена"); } } } listBoxUsers.DataSource = _users.ToList(); saveUsersToTxt(_users); MessageBox.Show("Готово"); }
//BASARSE EN ESTO PARA ARREGLAR TODO LO QUE SEA CON EL AD //Una mejor manera de hacerlo http://johnbarquin.wordpress.com/2008/06/12/servicios-de-directorio-en-net-35/ /// <summary> /// Método que se encarga de crear un usuario estudiante en Active Directory /// </summary> /// <param name="estudiante"> /// Los datos del estudiante (en un tipo Usuario) por ingresar a Active Directory /// </param> public Boolean crearEstudiante2(Usuario estudiante) { String nombre_completo = estudiante.Carnet + " " + estudiante.Nombre + " " + estudiante.Apellidos + " " + estudiante.Carrera; try { PrincipalContext contextoDominio = new PrincipalContext(ContextType.Domain, Constantes.DOM, Constantes.AD_USER, Constantes.AD_PASS); UserPrincipal usuario = new UserPrincipal(contextoDominio, estudiante.UID, estudiante.Contrasena, true); usuario.SamAccountName = estudiante.UID;// LEGACY: Cuenta de estudiante Pre-Win2000 usuario.UserPrincipalName = estudiante.UID + Constantes.DOMINIO;//Debe de contener el dominio usuario.GivenName = estudiante.Nombre; usuario.Surname = estudiante.Apellidos; usuario.DisplayName = nombre_completo; usuario.Description = "Estudiante"; usuario.HomeDirectory = getHomeDirectoryAD(estudiante); usuario.EmailAddress = estudiante.Correo; usuario.HomeDrive = "M"; usuario.PasswordNeverExpires = true; usuario.Save(); usuario.SetPassword(estudiante.Contrasena); usuario.Save(); return true; } catch (Exception e) { _conexionBD = new ManejoBD(); _conexionBD.insertarBitacoraError(e.ToString(), ""); return false; } }
public static List<Student> getMatchingStudents(string givenName, string surname) { List<Student> matches = new List<Student>(); using (PrincipalContext pc = new PrincipalContext( ContextType.ApplicationDirectory, "ailds01v.home.ad1.sou.edu:1556", "CN=Users,CN=University", ContextOptions.Negotiate | ContextOptions.SecureSocketLayer)) { SouPerson findPerson = new SouPerson(pc); findPerson.GivenName = givenName; findPerson.Surname = surname; PrincipalSearcher searcher = new PrincipalSearcher(findPerson); PrincipalSearchResult<Principal> results = searcher.FindAll(); foreach (SouPerson person in results) { if (person.souStudent == true) { Student s = new Student(); s.setKey1(person.souStudentKey1); s.setKey2(person.souStudentKey2); s.setUsername(person.Name); matches.Add(s); } } return matches; } }
public bool Login(String userName, String password) { PrincipalContext pc = new PrincipalContext(ContextType.Domain, this.domainName); bool isValid = false; isValid = pc.ValidateCredentials(userName, password); return isValid; }
private void ProcessOk() { try { PrincipalContext pcontext = new PrincipalContext(this.contextType, this.domain); using (pcontext) { if (pcontext.ValidateCredentials(this.user, this.textBoxPassword.Text, this.contextOptions) == false) { this.labelPassword.ForeColor = System.Drawing.Color.DarkRed; this.textBoxPassword.BackColor = System.Drawing.Color.Coral; this.pictureBoxLock.Visible = true; this.textBoxPassword.Select(); } else { this.password = this.textBoxPassword.Text; this.labelPassword.ForeColor = System.Drawing.Color.DarkGreen; this.textBoxPassword.BackColor = System.Drawing.Color.WhiteSmoke; this.pictureBoxLock.Visible = false; this.pictureBoxOpenLock.Visible = true; this.Refresh(); System.Threading.Thread.Sleep(400); this.Close(); } } } catch (Exception ex) { this.exception = ex; this.Close(); } }
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 IEnumerable<KeyValuePair<string, string>> GetSpecialistList(AdGroup grp) { var list = new Dictionary<string, string>(); using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { var domain = new PrincipalContext(ContextType.Domain); var group = GroupPrincipal.FindByIdentity(domain, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp)); if (group != null) { var members = group.GetMembers(true); foreach (var principal in members) { var userPrincipal = UserPrincipal.FindByIdentity(domain, principal.SamAccountName); if (userPrincipal != null) { var name = MainHelper.ShortName(userPrincipal.DisplayName); var sid = userPrincipal.Sid.Value; list.Add(sid, name); } } } return list.OrderBy(x => x.Value); } }
internal static bool SetClientRole(string loginName, BplRole role) { var result = false; try { using (var context = new PrincipalContext(ContextType.Domain, ADServer, ADUserContainer, ADUsername, ADPassword)) { var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, loginName); if (user != null) { var gpRole = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, (string)role.Id.LocalId); if (gpRole != null) { var grp = (DirectoryEntry)gpRole.GetUnderlyingObject(); grp.Properties["member"].Add(user.DistinguishedName); grp.CommitChanges(); grp.Close(); result = true; } else { Log.Warn("Auth: Group for role {0} was not found.", role.Id); } } else { Log.Warn("Auth: User {0} was not found.", loginName); } } } catch (Exception e) { Log.Exception(e, "Auth: Unable to set roles to user '{0}'", loginName); } return result; }
public void Run() { try { //open a users csv and start reading it StreamReader reader = new StreamReader(pathToUserCsv, true); //if headers, burn the first line if (hasHeaders) { reader.ReadLine(); } //read the rest of the file int count = 0; string line; while ((line = reader.ReadLine()) != null) { count++; //foreach user in file string[] columns = line.Split(','); //try without removing punctuation string fname = columns[1]; string lname = columns[3]; string samAccountName = columns[6]; string email = columns[5]; string password = columns[8]; try { using (var context = new PrincipalContext(ContextType.Domain, "student.rockhurst.int", "OU=2019,OU=Highly Managed,OU=Users,OU=Student.Greenlease,DC=student,DC=rockhurst,DC=int")) { using(var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName)) { user.SetPassword(password); } /*using (var user = new UserPrincipal(context)) { new accounts only user.SamAccountName = samAccountName; user.GivenName = fname; user.Surname = lname; user.EmailAddress = email; user.SetPassword(password); user.Enabled = true; user.Save(); }*/ } Console.WriteLine("ok: " + email); } catch (Exception ex) { Console.WriteLine("ex when email = " + email); Console.WriteLine(ex.Message); badSamAccountNames.Add(samAccountName); } } } catch (IOException e) { Console.WriteLine(e.Message); } Console.WriteLine("\n\nfails:"); foreach (string s in badSamAccountNames) { Console.WriteLine(s); } }
public bool IsUserMemberOfAccessControlGroup(string accessControlGroup) { if (string.IsNullOrWhiteSpace(accessControlGroup)) { return true; } PrincipalContext principalContext = new PrincipalContext(ContextType.Domain); GroupPrincipal groupPrincipal = GroupPrincipal .FindByIdentity(principalContext, accessControlGroup); if (groupPrincipal == null) { throw new FingertipsException("Could not find group: " + accessControlGroup); } UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Name); if (userPrincipal == null) { throw new FingertipsException("Could not find user: " + Name); } return userPrincipal.IsMemberOf(groupPrincipal); }
public LdapAuthentication() { LdapSettings.refreshLdapSettings(); var server = LdapSettings.LdapServer1; var admin = LdapSettings.LdapAdminUser; var pwd = LdapSettings.LdapAdminPassword; var container = LdapSettings.LdapContainer; try { _rootPrincipal = new PrincipalContext(ContextType.Domain, server, container, ContextOptions.Negotiate, admin, pwd); return; } catch (PrincipalServerDownException pex) { server = LdapSettings.LdapServer2; //_rootPrincipal = new PrincipalContext(ContextType.Domain, server, container, ContextOptions.Negotiate,admin, pwd); } try { _rootPrincipal = new PrincipalContext(ContextType.Domain, server, container, ContextOptions.Negotiate, admin, pwd); } catch (PrincipalServerDownException pex) { throw new LdapServerUnavailableException("Both ldap servers are down"); } }
public IHttpActionResult Authenticate(AuthenticationRequest authRequest) { bool valid = false; using (var context = new PrincipalContext(ContextType.Machine)) { if (Principal.FindByIdentity(context, authRequest.Username) != null) { valid = context.ValidateCredentials(authRequest.Username, authRequest.Password); } } if (valid) { OpaqueSecurityToken token = new OpaqueSecurityToken(); token.SecurePayload[OpaqueSecurityToken.KnownPayloadKeys.USERNAME] = authRequest.Username; token.SecurePayload[OpaqueSecurityToken.KnownPayloadKeys.TTL_SEC] = (60 * 60).ToString(); // 1 hour return Ok(new AuthenticationResponse() { AuthToken = token.SerializeToString(), AuthType = AuthMessageHandler.AuthenticationType, }); } //throw new HttpResponseException(HttpStatusCode.Unauthorized); return Content((HttpStatusCode)422, new AuthenticationResponse() { ErrorMessage = "Invalid username or password", }); }
public static bool ChangePassword(string sUserName, string oldPassword, string newPassword) { try { if (string.IsNullOrEmpty(ADISConstants.DomainOU)) { using (var context = new PrincipalContext(ContextType.Domain, ADISConstants.DomainNameOrIP, sUserName, oldPassword)) { using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName)) { //user.SetPassword("newpassword"); // or user.ChangePassword(oldPassword, newPassword); } } } else { using (var context = new PrincipalContext(ContextType.Domain, ADISConstants.DomainNameOrIP, ADISConstants.DomainOU, sUserName, oldPassword)) { using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName)) { //user.SetPassword("newpassword"); // or user.ChangePassword(oldPassword, newPassword); } } } return true; } catch(Exception ex) { throw ex; } }
public ActionResult Create([Bind(Include = "Nickname")] Player player) { if (ModelState.IsValid) { var name = User.Identity.Name; UserPrincipal user; using (var pc = new PrincipalContext(ContextType.Domain, "smausa")) { user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, name); } if (user == null) { throw new Exception("User not found!"); } player.Username = name; player.FirstName = user.GivenName; player.Surname = user.Surname; player.Email = user.EmailAddress; player.CreateDate = DateTime.Now; player.ActivityDate = new DateTime(1900, 1, 1); player.Mu = GameInfo.DefaultGameInfo.DefaultRating.Mean; player.Sigma = GameInfo.DefaultGameInfo.DefaultRating.StandardDeviation; player.Active = true; PlayerData.Create(player); Global.LoadPlayersOnly(); return RedirectToAction("Rankings"); } return View(player); }
public bool Validate(string userName, string password, out ClaimsIdentity oAuthIdentity, out ClaimsIdentity cookiesIdentity) { using (var ctx = new PrincipalContext(ContextType.Domain, DomainName)) { bool isValid = ctx.ValidateCredentials(userName, password); if (isValid) { oAuthIdentity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType); cookiesIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationType); var groups=GetUserGroups(userName); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userName)); cookiesIdentity.AddClaim(new Claim(ClaimTypes.Name, userName)); if (groups.Contains("BD")) { oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "BD")); cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, "BD")); } else { oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", groups))); cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", groups))); } } else { oAuthIdentity = null; cookiesIdentity = null; } return isValid; } }
public IEnumerable<EasyADUser> GetUsersInGroup(string groupName) { var users = new List<EasyADUser>(); using (var context = new PrincipalContext(ContextType.Domain)) { var group = GroupPrincipal.FindByIdentity(context, groupName); if (group == null) { return Enumerable.Empty<EasyADUser>(); } foreach (var principal in group.Members) { var user = principal as UserPrincipal; if (user == null || string.IsNullOrWhiteSpace(user.EmailAddress)) { continue; } users.Add(new EasyADUser { DisplayName = user.DisplayName, Email = user.EmailAddress, Login = user.SamAccountName }); } } return users; }
public ActionResult Create() { var name = User.Identity.Name; UserPrincipal user; using (var pc = new PrincipalContext(ContextType.Domain, "smausa")) { user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, name); } if (user == null) { throw new Exception("Active Directory user not found!"); } var player = new Player { Username = name, FirstName = user.GivenName, Surname = user.Surname, Email = user.EmailAddress, Notifications = !string.IsNullOrWhiteSpace(user.EmailAddress) }; return View(player); }
/// <summary> /// /// </summary> /// <param name="e"></param> protected void ADValidate(AuthenticateEventArgs e) { var domainForValidation = ConfigurationManager.AppSettings["IsHammerTime"] == "True" ? "BOMP" : ConfigurationManager.AppSettings["DomainForValidation"]; using (var pc = new PrincipalContext(ContextType.Domain, domainForValidation)) { //validate the credentials try { var isValid = pc.ValidateCredentials(LoginUser.UserName, LoginUser.Password); if (!isValid) return; Session.Add("credential",LoginUser.Password); e.Authenticated = true; var usuario = GetCredentialFromDb(); if (usuario != null) CreateEncryptedTicket(e, usuario.NombreCompleto); else { LoginUser.FailureText = "El usuario no tiene permisos para acceder a la aplicación."; e.Authenticated = false; } } catch (Exception exception) { LoginUser.FailureText = exception.Message; e.Authenticated = false; } } }
private static bool IsGroupMember(string userName, string Group) { #if DEBUG return true; //PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com", "fmedvedik", "(manos)3k"); //PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "10.0.0.2", "fmedvedik", "(manos)3k"); // PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com"); #else PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "reckner.com"); var findByIdentity = UserPrincipal.FindByIdentity(ctx, userName); bool retVal = false; if (findByIdentity != null) { List<string> result; using (var src = findByIdentity.GetGroups(ctx)) { result = new List<string>(); src.ToList().ForEach(sr => result.Add(sr.SamAccountName)); } var l = result.FirstOrDefault(s => s.Equals(Group)); retVal = (l != null); } ctx.Dispose(); return retVal; #endif }
public ComputerPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { if (samAccountName == null || password == null) { throw new ArgumentException(StringResources.NullArguments); } else { if (base.Context.ContextType != ContextType.ApplicationDirectory || !(base.GetType() == typeof(ComputerPrincipal))) { if (base.Context.ContextType != ContextType.ApplicationDirectory) { base.SamAccountName = samAccountName; } base.Name = samAccountName; base.SetPassword(password); base.Enabled = new bool?(enabled); return; } else { throw new InvalidOperationException(StringResources.ComputerInvalidForAppDirectoryStore); } } }
public bool Validate(string login, string pass) { using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain, DOMAIN, null, null)) { //Username and password for authentication. return(context.ValidateCredentials(login, pass)); } }
public Boolean contains(string username) { // Check grouplist is fresh if (groupmtime != File.GetLastWriteTimeUtc(pathgroups)) { ReadInGroupsFile(); } // if the groups file is empty then we always check the passwords if (grouplist.Count == 0) { writeLog("No groups found. User's password will be validated.", EventLogEntryType.Information); return(true); } PrincipalContext ctx = null; GroupPrincipal groupCtx = null; ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain); foreach (String groupname in grouplist) { //writeLog("trying [" + groupname + "]", EventLogEntryType.Information); groupCtx = GroupPrincipal.FindByIdentity(ctx, groupname); if (groupCtx != null) { //writeLog("found [" + groupCtx.ToString() + "]. Finding members", EventLogEntryType.Information); foreach (Principal user in groupCtx.GetMembers(true)) { if (user.SamAccountName == username) { writeLog("User " + username + " is in restricted group " + groupname + " and their password will be validated.", EventLogEntryType.Information); ctx.Dispose(); groupCtx.Dispose(); return(true); } } groupCtx.Dispose(); } } ctx.Dispose(); writeLog("User " + username + " is not in a restricted group", EventLogEntryType.Information); return(false); }
public static bool AuthenticateUser(string apiUser) { string username = ConfigurationManager.AppSettings["AllowedUsers"].ToString(); string[] users = username.Split(';'); if (users.Contains(apiUser)) { var context = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain, "ES-Area1"); var searchPrinciple = new UserPrincipal(context); searchPrinciple.SamAccountName = apiUser; PrincipalSearcher pS = new PrincipalSearcher(); pS.QueryFilter = searchPrinciple; //searches based on SamAccountName or DisplayName etc. //Perform the search PrincipalSearchResult <Principal> results = pS.FindAll(); if (results.ToList().Count > 0) { Principal pc = results.ToList()[0]; DirectoryEntry direEn = (DirectoryEntry)pc.GetUnderlyingObject(); Console.WriteLine("Email ID: " + direEn.Properties["mail"].Value.ToString()); Console.WriteLine("-------------------------------------------"); Console.WriteLine("First Name: " + direEn.Properties["givenName"].Value); Console.WriteLine("-------------------------------------------"); Console.WriteLine("Last Name : " + direEn.Properties["sn"].Value); Console.WriteLine("-------------------------------------------"); Console.WriteLine("SAM account name : " + direEn.Properties["samAccountName"].Value); Console.WriteLine("-------------------------------------------"); Console.WriteLine("User principal name: " + direEn.Properties["userPrincipalName"].Value); Console.WriteLine("-------------------------------------------"); Console.WriteLine(); return(true); } } return(false); }
public PrincipalContext(ContextType contextType, string name, string container) : this(contextType, name, container, PrincipalContext.GetDefaultOptionForStore(contextType), null, null) { }
public static GroupPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return((GroupPrincipal)Principal.FindByIdentityWithType(context, typeof(GroupPrincipal), identityValue)); }
// // Cross-store support // // Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that // represents a pointer to another store), maps that representation to the other store's StoreCtx and returns // a Principal from that other StoreCtx. The implementation of this method is highly dependent on the // details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to // interact with other StoreCtxs to fulfill the request. // // This method is typically used by ResultSet implementations, when they're iterating over a collection // (e.g., of group membership) and encounter an entry that represents a foreign principal. internal override Principal ResolveCrossStoreRefToPrincipal(object o) { Debug.Assert(o is DirectoryEntry); // Get the SID of the foreign principal DirectoryEntry foreignDE = (DirectoryEntry)o; if (foreignDE.Properties["objectSid"].Count == 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no objectSid found"); throw new PrincipalOperationException(SR.SAMStoreCtxCantRetrieveObjectSidForCrossStore); } Debug.Assert(foreignDE.Properties["objectSid"].Count == 1); byte[] sid = (byte[])foreignDE.Properties["objectSid"].Value; // Ask the OS to resolve the SID to its target. int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: LookupSid failed, err={0}, server={1}", err, this.MachineUserSuppliedName); throw new PrincipalOperationException( SR.Format(SR.SAMStoreCtxCantResolveSidForCrossStore, err)); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: LookupSid found {0} in {1}", name, domainName); // Since this is SAM, the remote principal must be an AD principal. // Build a PrincipalContext for the store which owns the principal // Use the ad default options so we turn sign and seal back on. #if USE_CTX_CACHE PrincipalContext remoteCtx = SDSCache.Domain.GetContext(domainName, _credentials, DefaultContextOptions.ADDefaultContextOption); #else PrincipalContext remoteCtx = new PrincipalContext( ContextType.Domain, domainName, null, (this.credentials != null ? credentials.UserName : null), (this.credentials != null ? credentials.Password : null), DefaultContextOptions.ADDefaultContextOption); #endif SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); Principal p = remoteCtx.QueryCtx.FindPrincipalByIdentRef( typeof(Principal), UrnScheme.SidScheme, sidObj.ToString(), DateTime.UtcNow); if (p != null) { return(p); } else { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no matching principal"); throw new PrincipalOperationException(SR.SAMStoreCtxFailedFindCrossStoreTarget); } }
public PrincipalContext(ContextType contextType, string name, string container, string userName, string password) : this(contextType, name, container, PrincipalContext.GetDefaultOptionForStore(contextType), userName, password) { }
public static new PrincipalSearchResult <ComputerPrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type) { return(FindByExpirationTime <ComputerPrincipal>(context, time, type)); }
public UserProxyFullPrincipal(PrincipalContext context) : base(context) { }
public static new PrincipalSearchResult <UserPrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return(FindByPasswordSetTime <UserPrincipal>(context, time, type)); }
public UserProxyFullPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : base(context, samAccountName, password, enabled) { }
public static Principal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return(FindByIdentityWithType(context, typeof(Principal), identityType, identityValue)); }
public static new UserPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return((UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityValue)); }
public void Save(PrincipalContext context) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Entering Save(Context)"); // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Make sure we're not a fake principal CheckFakePrincipal(); // We must have a PrincipalContext to save into. This should always be the case, unless we're unpersisted // and they never set a PrincipalContext. if (context == null) { Debug.Assert(this.unpersisted == true); throw new InvalidOperationException(SR.NullArguments); } if (context.ContextType == ContextType.Machine || _ctx.ContextType == ContextType.Machine) { throw new InvalidOperationException(SR.SaveToNotSupportedAgainstMachineStore); } // If the user is trying to save to the same context we are already set to then just save the changes if (context == _ctx) { Save(); return; } // If we already have a context set on this object then make sure the new // context is of the same type. if (context.ContextType != _ctx.ContextType) { Debug.Assert(this.unpersisted == true); throw new InvalidOperationException(SR.SaveToMustHaveSamecontextType); } StoreCtx originalStoreCtx = GetStoreCtxToUse(); _ctx = context; // Call the appropriate operation depending on whether this is an insert or update StoreCtx newStoreCtx = GetStoreCtxToUse(); Debug.Assert(newStoreCtx != null); // since we know this.ctx isn't null Debug.Assert(originalStoreCtx != null); // since we know this.ctx isn't null if (this.unpersisted) { // We have an unpersisted principal so we just want to create a principal in the new store. GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): inserting new principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType()); Debug.Assert(newStoreCtx == _ctx.ContextForType(this.GetType())); newStoreCtx.Insert(this); this.unpersisted = false; // once we persist, we're no longer in the unpersisted state } else { // We have a principal that already exists. We need to move it to the new store. GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Save(context): Moving principal of type {0} using {1}", this.GetType(), newStoreCtx.GetType()); // we are now saving to a new store so this principal is unpersisted. this.unpersisted = true; // If the user has modified the name save away the current name so // if the move succeeds and the update fails we will move the item back to the original // store with the original name. bool nameModified = _nameChanged == LoadState.Changed; string previousName = null; if (nameModified) { string newName = _name; _ctx.QueryCtx.Load(this, PropertyNames.PrincipalName); previousName = _name; this.Name = newName; } newStoreCtx.Move(originalStoreCtx, this); try { this.unpersisted = false; // once we persist, we're no longer in the unpersisted state newStoreCtx.Update(this); } catch (System.SystemException e) { try { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Update Failed (attempting to move back) Exception {0} ", e.Message); if (nameModified) { this.Name = previousName; } originalStoreCtx.Move(newStoreCtx, this); GlobalDebug.WriteLineIf(GlobalDebug.Info, "Principal", "Move back succeeded"); } catch (System.SystemException deleteFail) { // The move back failed. Just continue we will throw the original exception below. GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Move back Failed {0} ", deleteFail.Message); } if (e is System.Runtime.InteropServices.COMException) { throw ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e); } else { throw; } } } _ctx.QueryCtx = newStoreCtx; // so Updates go to the right StoreCtx }
protected static PrincipalSearchResult <AuthenticablePrincipal> FindByLogonTime <T>(PrincipalContext context, DateTime time, MatchType type) { AuthenticablePrincipal.CheckFindByArgs(context, time, type, typeof(T)); return(new PrincipalSearchResult <T>(context.QueryCtx.FindByLogonTime(time, type, typeof(T)))); }
// // QBE // static public void BuildQbeFilter(Principal p) { PrincipalContext ctx = PrincipalContext.Test; ((TestStoreCtx)ctx.QueryCtx).CallBuildQbeFilterDescription(p); }
// // Public Constructors // public PrincipalContext(ContextType contextType) : this(contextType, null, null, PrincipalContext.GetDefaultOptionForStore(contextType), null, null) { }
public static new PrincipalSearchResult <ComputerPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return(FindByBadPasswordAttempt <ComputerPrincipal>(context, time, type)); }
protected static PrincipalSearchResult <T> FindByPasswordSetTime <T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return(new PrincipalSearchResult <T>(context.QueryCtx.FindByPasswordSetTime(time, type, typeof(T)))); }
public static PrincipalSearchResult <UserPrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type) { return(AuthenticablePrincipal.FindByLogonTime <UserPrincipal>(context, time, type)); }
public static PrincipalSearchResult <AuthenticablePrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return(FindByPasswordSetTime <AuthenticablePrincipal>(context, time, type)); }
static internal Principal ConstructFakePrincipalFromSID( byte[] sid, PrincipalContext ctx, string serverName, NetCred credentials, string authorityName) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Utils", "ConstructFakePrincipalFromSID: Build principal for SID={0}, server={1}, authority={2}", Utils.ByteArrayToString(sid), (serverName != null ? serverName : "NULL"), (authorityName != null ? authorityName : "NULL")); Debug.Assert(ClassifySID(sid) == SidType.FakeObject); // Get the name for it string nt4Name = ""; int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(serverName, credentials, sid, out name, out domainName, out accountUsage); if (err == 0) { // If it failed, we'll just live without a name //Debug.Assert(accountUsage == 5 /*WellKnownGroup*/); nt4Name = (!string.IsNullOrEmpty(domainName) ? domainName + "\\" : "") + name; } else { GlobalDebug.WriteLineIf( GlobalDebug.Warn, "Utils", "ConstructFakePrincipalFromSID: LookupSid failed (ignoring), serverName=" + serverName + ", err=" + err); } // Since LookupAccountSid indicates all of the NT AUTHORITY, etc., SIDs are WellKnownGroups, // we'll map them all to Group. // Create a Principal object to represent it GroupPrincipal g = GroupPrincipal.MakeGroup(ctx); g.fakePrincipal = true; g.unpersisted = false; // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalDisplayName, nt4Name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalName, name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSamAccountName, name); // SID IdentityClaim SecurityIdentifier sidObj = new SecurityIdentifier(Utils.ConvertSidToSDDL(sid)); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSid, sidObj); g.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, true); return(g); }
private static UserPrincipal _FindDomainUserBySamAccountName(string samAccoutName) { using (var context = new PrincipalContext(ContextType.Domain)) return(UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccoutName)); }
public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions) { string contextName = name; string userName = null; bool explicitCreds = false; if (credentials != null && credentials.UserName != null) { if (credentials.Domain != null) { userName = credentials.Domain + "\\" + credentials.UserName; } else { userName = credentials.UserName; } explicitCreds = true; } else { userName = Utils.GetNT4UserName(); } GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}", name, userName, explicitCreds.ToString(), contextOptions.ToString()); if (!_isSAM) { // Determine the domain DNS name // DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY int flags = unchecked ((int)(0x40000000 | 0x00000010 | 0x00000100)); UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags); contextName = info.DomainName; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName); ManualResetEvent contextReadyEvent = null; while (true) { Hashtable credTable = null; PrincipalContext ctx = null; // Wait for the PrincipalContext to be ready if (contextReadyEvent != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting"); contextReadyEvent.WaitOne(); } contextReadyEvent = null; lock (_tableLock) { CredHolder credHolder = (CredHolder)_table[contextName]; if (credHolder != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName); credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); Debug.Assert(credTable != null); object o = credTable[userName]; if (o is Placeholder) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder"); // A PrincipalContext is currently being constructed by another thread. // Wait for it. contextReadyEvent = ((Placeholder)o).contextReadyEvent; continue; } WeakReference refToContext = o as WeakReference; if (refToContext != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null"); ctx = (PrincipalContext)refToContext.Target; // null if GC'ed // If the PrincipalContext hasn't been GCed or disposed, use it. // Otherwise, we'll need to create a new one if (ctx != null && ctx.Disposed == false) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext"); return(ctx); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing"); credTable.Remove(userName); } } } // Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable // are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext. if (credHolder == null) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString()); // No contexts exist for the contextName. Create a CredHolder for the contextName so we have a place // to store the PrincipalContext we'll be creating. credHolder = new CredHolder(); _table[contextName] = credHolder; credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds); } // Put a placeholder on the contextName/userName slot, so that other threads that come along after // we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us credTable[userName] = new Placeholder(); } // Now we just need to create a PrincipalContext for the contextName and credentials GlobalDebug.WriteLineIf( GlobalDebug.Info, "SDSCache", "GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString()); ctx = new PrincipalContext( (_isSAM ? ContextType.Machine : ContextType.Domain), contextName, null, contextOptions, (credentials != null ? credentials.UserName : null), (credentials != null ? credentials.Password : null) ); lock (_tableLock) { Placeholder placeHolder = (Placeholder)credTable[userName]; // Replace the placeholder with the newly-created PrincipalContext credTable[userName] = new WeakReference(ctx); // Signal waiting threads to continue. We do this after inserting the PrincipalContext // into the table, so that the PrincipalContext is ready as soon as the other threads wake up. // (Actually, the order probably doesn't matter, since even if we did it in the // opposite order and the other thread woke up before we inserted the PrincipalContext, it would // just block as soon as it tries to acquire the tableLock that we're currently holding.) bool f = placeHolder.contextReadyEvent.Set(); Debug.Assert(f == true); } return(ctx); } }
public static PrincipalSearchResult <UserPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return(AuthenticablePrincipal.FindByBadPasswordAttempt <UserPrincipal>(context, time, type)); }
protected void fillBtn_Click(object sender, EventArgs e) { if ( isNull() ) return; using ( PrincipalContext context = new PrincipalContext( ContextType.Domain, "ITSERVICES" ) ) { ComputerPrincipal computer = new ComputerPrincipal( context ); computer.Name = ComputerTextBox.Text; using ( PrincipalSearcher searcher = new PrincipalSearcher( computer ) ) { Principal result = searcher.FindOne(); AuthenticablePrincipal auth = result as AuthenticablePrincipal; if ( auth != null ) { lblName.Text = auth.Name; lblLastLogon.Text = auth.LastLogon.ToString(); lblEnabled.Text = auth.Enabled.ToString(); lblDistinguishedName.Text = auth.DistinguishedName; } } } ComputerPanel.Visible = true; }