public ActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { var logon = new ActiveDirectory(model.Username); var response = logon.Logon(model.Password); if (response == WindowsLogonResponse.Successful || response == WindowsLogonResponse.PasswordChangeRequired) WebsiteUser.Login(model.Username); if (response == WindowsLogonResponse.Successful) return RedirectToAction("Index", "Home"); if (response == WindowsLogonResponse.PasswordChangeRequired) { TempData["Notice"] = "You are required to change your password."; return RedirectToAction("ChangePassword", "Home"); } ModelState.AddModelError( "Invalid", response == WindowsLogonResponse.LockedOut ? "Take a chill pill. Stop trying for a while." : "Invalid username and/or password"); return View(); } return View(); }
static void Main(string[] args) { Console.WriteLine("Enter the domain name"); var domainName = Console.ReadLine(); // Set credentials of the user account that we will use to perform the domain // the active directory operations. This user must have access to the AD Console.WriteLine("Enter the operating user name"); var operatingUsername = Console.ReadLine(); Console.WriteLine("Enter the operating user password"); var operatingUserPassword = Console.ReadLine(); // Instantiate the class using the variables above Console.WriteLine("Test reading entire Active Directory"); var activeDirectory = new ActiveDirectory(domainName,operatingUsername,operatingUserPassword); activeDirectory.Populate(true); // Authenticate a user Console.WriteLine("Testing user authentication"); Console.WriteLine("Enter the user name"); var username = Console.ReadLine(); Console.WriteLine("Enter the password"); var password = Console.ReadLine(); if (activeDirectory.AuthenticateUser(username, password)) { Console.WriteLine("You have been authenticated"); } else { Console.WriteLine("User/Password combination is incorrect"); } Console.ReadKey(); }
public ActionResult Index() { var ad = new ActiveDirectory(WebsiteUser.Username); var user = ad.GetUserPrincipal(); if (user == null) return RedirectToAction("Logout", "Auth"); var entry = (System.DirectoryServices.DirectoryEntry)user.GetUnderlyingObject(); var native = (ActiveDs.IADsUser)entry.NativeObject; return View( new UserModel { PasswordExpiration = native.PasswordExpirationDate <= new DateTime(1980, 1, 1) ? null : (DateTime?)native.PasswordExpirationDate, DisplayName = user.DisplayName, EmailAddress = user.EmailAddress, LastPasswordSet = user.LastPasswordSet, PasswordNeverExpires = user.PasswordNeverExpires }); }
public ActionResult AddUser(int id, string userName) { HasPermission("AssignUserToRole"); var role = ask.FindRoleById(id); var user = ActiveDirectory.GetUser(userName, AppSettings.ActiveDirDomain); command.AddUserToRoleAndCreateUserIfNotExist(user.ToDbUser(), role.Id, UserName); return(RedirectToAction("Details", new { id = id, tab = "user" })); }
public async Task Load_Should_Fetch_Data() { var settings = ActiveDirectory.GetProductionSettings(); var client = new ActiveDirectoryClientProvider(settings).Get(); var cache = new InMemoryAvatarCache(client); var avatars = await cache.Get(); avatars.Count.Should().BeGreaterThan(0); }
public string GetDomainDN(string domain) { string DN = String.Empty; ActiveDirectory ad = new ActiveDirectory(); DN = ad.GetDomainDN(domain); return(DN); }
private Tuple <ActiveDirectory, string> AuthenticateUser(HttpContext httpContext) //Authenticate User by their Username stored in the cookies. { if (HttpContext.User.Identity.IsAuthenticated) { string UserName = HttpContext.User.Claims.Where(user => user.Type == "UserName").First().Value; var User = new ActiveDirectory(UserName); return(new Tuple <ActiveDirectory, string>(User, UserName)); } return(null); }
/// <summary> /// Enumerates certificate templates registered in Active Directory. /// </summary> /// <returns>An array of certificate templates.</returns> public static CertificateTemplate[] EnumTemplates() { if (ActiveDirectory.Ping()) { String cn = "CN=Certificate Templates, CN=Public Key Services, CN=Services," + ActiveDirectory.ConfigContext; DirectoryEntries entries = ActiveDirectory.GetChildItems(cn); return((from DirectoryEntry item in entries select new CertificateTemplate("name", (String)item.Properties["cn"].Value)).ToArray()); } throw new Exception(Error.E_DCUNAVAILABLE); }
public void TestInitialize() { this.directory = new ActiveDirectory(); this.sam = new LocalSam(Mock.Of <ILogger <LocalSam> >()); this.mockSam = new Mock <ILocalSam>(); this.mockSettings = new Mock <IJitSettings>(); this.groupResolver = new Mock <IJitAccessGroupResolver>(); this.agent = new JitAgent(Mock.Of <ILogger <JitAgent> >(), this.directory, this.mockSettings.Object, this.mockSam.Object, this.groupResolver.Object); }
/// <summary> /// Deletes a group from Active Directory. /// </summary> /// <param name="ad">An Active Directory object used to delete the group.</param> /// <param name="guid">The GUID of the group.</param> /// <returns>True if the group was deleted, false otherwise.</returns> static public bool Delete(ActiveDirectory ad, Guid guid) { if (ad != null && guid != Guid.Empty) { return(ad.Delete(guid)); } else { return(false); } }
/// <summary> /// /// </summary> /// <returns></returns> virtual protected bool IsUserAuthenticated() { if (!ActiveDirectory.IsAuthenticated(Request.userPrincipal)) { OnAuthenticationFailed(); return(false); } OnAuthenticationSuccessful(); return(true); }
public void GetData() { using (var ctx = new SolutionsContext()) { this.Name = ActiveDirectory.GetName(this.Account); this.Permissions = ctx.Permissions .Where(x => x.EmployeeId == this.Id) .AsNoTracking() .ToList(); } }
/// <summary> /// Use the connection form to connect to specified AD /// </summary> private void FormConnect() { EnableCurtain(); ActiveDirectory.Connect(); ActiveDirectory.Connector.ProgressChanged += Connector_ProgressChanged; ActiveDirectory.Connector.RunWorkerCompleted += Connector_Completed; StatusProgress.Visibility = Visibility.Visible; StatusMessage.Visibility = Visibility.Visible; }
public HttpResponseMessage CheckADObject(string adObject) { HttpResponseMessage response = new HttpResponseMessage(); ADObjectCheckResult result = new ADObjectCheckResult(); result = ActiveDirectory.CheckADObjectType(adObject); response = Request.CreateResponse(HttpStatusCode.OK, result); return(response); }
public HttpResponseMessage IsMemberOf(string user, [FromUri] string group) { HttpResponseMessage response = new HttpResponseMessage(); MembershipResult result = new MembershipResult(); result.isMember = ActiveDirectory.IsUserMemberOf(user, group); response = Request.CreateResponse(HttpStatusCode.OK, result); return(response); }
public ActionResult AddUser(string userName) { HasPermission("AddUser"); var user = ActiveDirectory .GetUser(userName, AppSettings.ActiveDirDomain) .ToDbUser(); command.AddUserIfNotExisted(user, UserName); return(RedirectToAction("Index")); }
private void getInfoData() { StorageService.CreateStorage(); string eml = StorageService.InfoData.Email == null ? "unknown" : StorageService.InfoData.Email; email.Text = eml.Length > 20 ? $"{eml.Substring(0, 20)}..." : eml; domainName.Text = ActiveDirectory.GetDomain(); serverName.Text = ActiveDirectory.GetServerName(); UpdateTable(); UpdatePreviousDate(); }
public static ActiveDirectoryDto ToDto(this ActiveDirectory ad) { if (ad == null) { return(null); } return(new ActiveDirectoryDto { Domain = ad.Domain, Id = ad.Id }); }
public HttpResponseMessage UserGroupMembership(string user) { HttpResponseMessage response = new HttpResponseMessage(); UserMembershipResult result = new UserMembershipResult(); result.user = user; result = ActiveDirectory.GetAllGroupsByUser(result); response = Request.CreateResponse(HttpStatusCode.OK, result); return(response); }
public HomeController(ActiveDirectory activeDirectory, ICustomerApplicationService customerService, ITaskApplicationService taskService, IUserApplicationService userService, IProjectApplicationService projectService) { ActiveDirectory = activeDirectory; CustomerService = customerService; TaskService = taskService; UserService = userService; ProjectService = projectService; }
public ActionResult UserProfile() { string serverName = ConfigurationManager.AppSettings["ADServer"]; string userName = ConfigurationManager.AppSettings["ADUserName"]; string password = ConfigurationManager.AppSettings["ADPassword"]; if (System.Web.HttpContext.Current.User.Identity.Name != "jbrennan") { return(RedirectToAction("Index", "Home")); } SecureString securePwd = null; if (password != null) { securePwd = new SecureString(); foreach (char chr in password.ToCharArray()) { securePwd.AppendChar(chr); } } UserProfile usrProfile = new UserProfile(); try { ActiveDirectory adConnect = new ActiveDirectory(serverName, userName, securePwd); List <SearchResultEntry> results = adConnect.GetEntriesBySAMAccountName(System.Web.HttpContext.Current.User.Identity.Name); if (results.Count > 0) { User usr = new User(adConnect, results[0]); usrProfile.FirstName = usr.FirstName; usrProfile.LastName = usr.LastName; usrProfile.Manager = usr.Manager; usrProfile.Department = usr.Department; usrProfile.Division = usr.Division; usrProfile.EmployeeId = usr.EmployeeId; usrProfile.EmployeeNumber = usr.EmployeeNumber; usrProfile.PhoneNumber = usr.PhoneNumber; usrProfile.StreetAddress = usr.StreetAddress; usrProfile.Title = usr.Title; usrProfile.UserName = usr.DisplayName; usrProfile.Groups = usr.Groups; } } catch { // unable to connect AD ModelState.AddModelError("", "Unable to connect AD!"); var emailBody = "CARS AD Failure for user: "******"*****@*****.**", "*****@*****.**", emailBody); } return(View(usrProfile)); }
private Tuple <ActiveDirectory, string> AuthenticateUser(HttpContext httpContext) { if (HttpContext.User.Identity.IsAuthenticated) { string UserName = HttpContext.User.Claims.Where(user => user.Type == "UserName").First().Value; // Gets Username from a claim in cookies var User = new ActiveDirectory(UserName); if (User.role == "Staff") // Tests if the authenticated user is a staff member { return(new Tuple <ActiveDirectory, string>(User, UserName)); } } return(null); }
private void Refresh() { IEnumerable <USER> activeDirectoryUSERS = ActiveDirectory.GetUSERS(); IEnumerable <USER> existingUSERS = getExistingUSERSFunc(); foreach (var activeDirectoryUSER in activeDirectoryUSERS) { if (!existingUSERS.Any(x => x.NAME == activeDirectoryUSER.NAME)) { Entities.Add(activeDirectoryUSER); } } }
/// <summary> /// User refresh button action /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RefreshButton_Click(object sender, RoutedEventArgs e) { ResultBox.Visibility = Visibility.Hidden; RefreshButton.IsEnabled = false; RefreshButton.Content = null; RefreshProgress.Visibility = Visibility.Visible; RefreshProgressMessage.Visibility = Visibility.Visible; RefreshProgressMessage.Text = "Refreshing..."; ActiveDirectory.Refresh("Users"); }
private async Task ConnectAD() { bool isConnect = await ActiveDirectory.Connect(); if (isConnect) { DisplayOtherForm(new ActiveDirectoryForm()); } else { DisplayOtherForm(new LoginADForm()); } }
void m_fillproperties(String ldapPath) { IDictionary <String, Object> props = ActiveDirectory.GetEntryProperties( ldapPath, ActiveDirectory.PropCN, ActiveDirectory.PropDN, ActiveDirectory.PropDisplayName, ActiveDirectory.PropFlags, ActiveDirectory.PropCpsOid, ActiveDirectory.PropCertTemplateOid, ActiveDirectory.PropLocalizedOid, ActiveDirectory.PropPkiTemplateMajorVersion, ActiveDirectory.PropPkiTemplateMinorVersion, ActiveDirectory.PropPkiSchemaVersion, ActiveDirectory.PropWhenChanged, ActiveDirectory.PropPkiSubjectFlags, ActiveDirectory.PropPkiEnrollFlags, ActiveDirectory.PropPkiPKeyFlags, ActiveDirectory.PropPkiNotAfter, ActiveDirectory.PropPkiRenewalPeriod, ActiveDirectory.PropPkiPathLength, ActiveDirectory.PropCertTemplateEKU, ActiveDirectory.PropPkiCertPolicy, ActiveDirectory.PropPkiCriticalExt, ActiveDirectory.PropPkiSupersede, ActiveDirectory.PropPkiKeyCsp, ActiveDirectory.PropPkiKeySize, ActiveDirectory.PropPkiKeySpec, ActiveDirectory.PropPkiKeySddl, ActiveDirectory.PropPkiRaAppPolicy, ActiveDirectory.PropPkiRaCertPolicy, ActiveDirectory.PropPkiRaSignature, ActiveDirectory.PropPkiAsymAlgo, ActiveDirectory.PropPkiSymAlgo, ActiveDirectory.PropPkiSymLength, ActiveDirectory.PropPkiHashAlgo, ActiveDirectory.PropPkiKeyUsage, ActiveDirectory.PropPkiKeyUsageCng ); flags = (Int32)props[ActiveDirectory.PropFlags]; Name = (String)props[ActiveDirectory.PropCN]; DistinguishedName = (String)props[ActiveDirectory.PropDN]; DisplayName = (String)props[ActiveDirectory.PropDisplayName]; major = (Int32)props[ActiveDirectory.PropPkiTemplateMajorVersion]; minor = (Int32)props[ActiveDirectory.PropPkiTemplateMinorVersion]; SchemaVersion = (Int32)props[ActiveDirectory.PropPkiSchemaVersion]; OID = new Oid((String)props[ActiveDirectory.PropCertTemplateOid]); LastWriteTime = (DateTime)props[ActiveDirectory.PropWhenChanged]; Settings = new CertificateTemplateSettings(props); }
static public List <Dictionary <String, String> > insertFreeDayAlsoBlocks(String fullName, DateTime _startDate, DateTime _endDate, String _Comment) { ActiveDirectory activeDirectory = new ActiveDirectory(); String _id = activeDirectory.Get_Fixed_Name(fullName); if (_id != "Cant Get Fixed Name" && _id != "Get Multiple Fixed Name") { String employeeName = activeDirectory.Get_Fixed_Name_id(_id); String manager_id = activeDirectory.Get_Name(_id, "manager").Split('=').ToArray <String>()[1].Substring(0, 8); String manager_name = activeDirectory.Get_Fixed_Name_id(manager_id); employeeName = employeeName.Replace("'", "''"); String startDate = _startDate.ToString("yyyy-MM-dd HH:mm:ss"); String endDate = _endDate.ToString("yyyy-MM-dd HH:mm:ss"); String dateNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); using (MySqlConnection Conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["customersConnectionString"].ConnectionString)) { MySqlCommand Command = new MySqlCommand(@"Insert into fortigate.FreeDayEmployee (employee_id, employee_name, manager_name, startDate, endDate, comment, initialDate) Values('" + _id + "','" + employeeName + "','" + manager_name + "','" + startDate + "','" + endDate + "','" + _Comment + "','" + dateNow + "');", Conn); Conn.Open(); try { Command.ExecuteNonQuery(); } catch { } finally { Conn.Close(); } } return(null); } else if (_id == "Cant Get Fixed Name") { List <Dictionary <String, String> > error_message_list = new List <Dictionary <String, String> >(); Dictionary <String, String> error_message = new Dictionary <String, String>(); error_message.Add("error_message", "Cant Get Fixed Name"); error_message_list.Add(error_message); return(error_message_list); } else if (_id == "Get Multiple Fixed Name") { List <Dictionary <String, String> > error_message_list = new List <Dictionary <String, String> >(); Dictionary <String, String> error_message = new Dictionary <String, String>(); error_message.Add("error_message", "Get Multiple Fixed Name"); error_message_list.Add(error_message); return(error_message_list); } return(null); }
public string GetGroups(string UserName) { string result = ""; if (UserName != "") { string serverName = ConfigurationManager.AppSettings["ADServer"]; string userName = ConfigurationManager.AppSettings["ADUserName"]; string password = ConfigurationManager.AppSettings["ADPassword"]; SecureString securePwd = null; if (password != null) { securePwd = new SecureString(); foreach (char chr in password.ToCharArray()) { securePwd.AppendChar(chr); } } try { ActiveDirectory adConnectGroup = new ActiveDirectory(serverName, userName, securePwd); UserProfile usrProfile = new UserProfile(); List <SearchResultEntry> results = adConnectGroup.GetEntriesBySAMAccountName(UserName); if (results.Count > 0) { User usr = new User(adConnectGroup, results[0]); usrProfile.Groups = usr.Groups; StringBuilder sb = new StringBuilder(); foreach (string group in usrProfile.Groups) { sb.Append(group.ToString()); } string strGroups = sb.ToString(); result = strGroups; } } catch { result = "An error occured retreiving group membership."; } return(result); } else { result = "Log in to see Group Memberships"; return(result); } }
private dynamic MergeUsers(List <dynamic> subscriptionsData) { var adUsers = ActiveDirectory.List(); IDictionary <string, dynamic> fbUsers = API.Firebase.GetAllUsers(); foreach (var s in subscriptionsData) { string email = ""; string name = ""; if (s.CcnEmail.Equals(DBNull.Value)) { if (!s.CcnUsername.Equals(DBNull.Value)) { string adEntry = adUsers.Keys.Where(x => x.Equals(s.CcnUsername, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); var ad = adUsers[adEntry]; if (ad != null) { email = ad.EmailAddress; name = ad.GivenName + " " + ad.Surname; } } else if (!s.SbrUserId.Equals(DBNull.Value)) { var fbEntry = fbUsers.Keys.Where(y => y.Equals(s.SbrUserId)).FirstOrDefault(); if (fbEntry != null) { if (fbUsers.ContainsKey(fbEntry)) { var fb = fbUsers[fbEntry]; if (fb != null) { email = fb.Email; name = fb.DisplayName; } } } } else { continue; } s.CcnEmail = email; s.FullName = name; } } return(subscriptionsData.Where(x => !String.IsNullOrEmpty(x.CcnEmail))); }
public async Task <ActiveDirectory> Put(int id, [FromBody] ActiveDirectory entity) { logger.LogDebug("Entered ActiveDirectory Controller Put Action"); try { await this.CurrentService.Update(entity); return(entity); } catch (Exception ex) { throw ex; } }
public override string[] GetRolesForUser(string domainUsername) { string email = ActiveDirectory.IdentityUserEmailFromActiveDirectory(domainUsername); //находим пользователя по его email var applicationUserDTO = SecurityService.GetIdentityUser(email); List <string> result = new List <string>(); foreach (var roleId in applicationUserDTO.RolesID) { result.Add(SecurityService.GetRoleById(roleId)); } return(result.ToArray()); }
/// <summary> /// Constructor /// </summary> /// <param name="request"></param> /// <param name="validator"></param> protected BaseTemplate(JSONRPC_API request, IValidator <T> validator) { Ado = new ADO("defaultConnection"); if (ActiveDirectory.IsAuthenticated(request.userPrincipal)) { SamAccountName = request.userPrincipal.SamAccountName.ToString(); } Request = request; Response = new JSONRPC_Output(); Validator = validator; Trace_BSO_Create.Execute(Ado, request); }
/// <summary> /// 变更用户密码 /// </summary> /// <param name="user">用户</param> /// <param name="ad"></param> /// <param name="ou">用户隶属于组</param> public void ChangeUserPassword(User user, ActiveDirectory ad, ActiveDirectoryGroup group) { var ou = GetOU(group); var adInfo = ad; //user.ActiveDirectory; var domainPath = GetDomainPath(adInfo.LDAPRoot, adInfo.DCInfo, ou, "CN=" + user.UserName); using (var de = new DirectoryEntry(domainPath, adInfo.AdminName, adInfo.AdminPwd, AuthenticationTypes.Secure)) { var pass = Utility.DecryptText(user.Password, user.PrivateKey); de.Invoke("SetPassword", new object[] { pass }); de.CommitChanges(); de.RefreshCache(); } }
public ActionResult ChangePassword(ChangePasswordModel model) { // let's check to see if the user is allowed to change their password var ad = new ActiveDirectory(WebsiteUser.Username); if (ad.UserCannotChangePassword()) return View("UnableToChangePassword"); if (!ModelState.IsValid) { return View(new ChangePasswordModel()); } try { ad.ChangePassword(model.OldPassword, model.NewPassword); TempData["Success"] = "Password successfully changed!"; return RedirectToAction("Index"); } catch (PasswordException) { ModelState.AddModelError("PasswordFailed", "Changing of your password failed. Please ensure the new password meets complexity requirements, hasn't been used previously, or if the old password does not match."); } return View(new ChangePasswordModel()); }
public ActiveDirectoryOrganizationalUnit(ActiveDirectory activeDirectory, string path, bool retrieveDescendants = false, int? depth = null) : this(activeDirectory.OperatingUsername, activeDirectory.OperatingUserPassword, path, retrieveDescendants, depth) { }
public ActionResult ChangePassword() { // let's check to see if the user is allowed to change their password var ad = new ActiveDirectory(WebsiteUser.Username); return ad.UserCannotChangePassword() ? View("UnableToChangePassword") : View(new ChangePasswordModel()); }