/* void OnPostAuthenticateRequest( object sender, EventArgs e ) { //var app = (HttpApplication)sender; //OnAuthenticate(app.Context); } */ /// <summary> /// Authenticates the current context. /// </summary> /// <param name="context">The context containing the current request to be authenticated and the response.</param> public static void OnAuthenticate( HttpContext context ) { if (!CheckRequireAuthentication(context)) return; var ticketCookie = HttpContext.Current.Request.Cookies[AuthenticationTicketTokenKey]; var ticketHeader = HttpContext.Current.Request.Headers["X-" + AuthenticationTicketTokenKey]; var rememberCookie = HttpContext.Current.Request.Cookies[RememberMeKey]; var rememberHeader = HttpContext.Current.Request.Headers["X-" + RememberMeKey]; var sessionCookie = HttpContext.Current.Request.Cookies[SessionIdKey]; var sessionHeader = HttpContext.Current.Request.Headers["X-" + SessionIdKey]; var rememberMe = false; if (rememberCookie != null && !String.IsNullOrWhiteSpace(rememberCookie.Value)) Boolean.TryParse(rememberCookie.Value, out rememberMe); else if (!String.IsNullOrWhiteSpace(rememberHeader)) Boolean.TryParse(rememberHeader, out rememberMe); var ipAddress = context.Request.UserHostAddress; if ((ticketCookie == null || string.IsNullOrWhiteSpace(ticketCookie.Value)) && string.IsNullOrWhiteSpace(ticketHeader)) { Guid anonSessionId; if ((sessionCookie == null || string.IsNullOrWhiteSpace(sessionCookie.Value)) && string.IsNullOrWhiteSpace(sessionHeader)) { anonSessionId = Guid.NewGuid(); } else { anonSessionId = Guid.Parse(sessionHeader ?? sessionCookie.Value); } var anon = new UserPrincipal(); //anonymous anon.Identity.Ticket.UserSession.RenewalToken = anonSessionId; anon.Identity.Ticket.IPAddress = ipAddress; SecurityContextManager.CurrentUser = anon; return; } var identity = UserManager.AuthenticateUser(ticketHeader ?? ticketCookie.Value, rememberMe ? UserSessionDurationType.Extended : UserSessionDurationType.PublicComputer, ipAddress, new ExecutionResults()); var principal = new UserPrincipal(identity); SecurityContextManager.CurrentUser = principal; if (ImpersonationEnabled && !principal.IsAnonymous && principal.IsInAnyRole(UserManager.Provider.ImpersonationAllowedRoles)) { //check for impersonation HttpCookie impersonatedUserCookie = context.Request.Cookies[ImpersonationKey]; var impersonatedHeader = context.Request.Headers["X-" + ImpersonationKey]; if (!String.IsNullOrWhiteSpace(impersonatedHeader) || (impersonatedUserCookie != null && !string.IsNullOrEmpty(impersonatedUserCookie.Value))) { var impersonatedUser = UserManager.GetUserByName(impersonatedHeader ?? impersonatedUserCookie.Value); if (impersonatedUser != null) { principal = new UserPrincipal(new UserIdentity(impersonatedUser.UserID, impersonatedUser.Name, identity)); SecurityContextManager.CurrentUser = principal; } } } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); UserPrincipal principal = new UserPrincipal(ticket.Name); HttpContext.Current.User = principal; } }
/// <summary> /// Authenticate the request. /// Using Custom Forms Authentication since I'm not using the "RolesProvider". /// Roles are manually stored / encrypted in a cookie in <see cref="FormsAuthenticationService.SignIn"/> /// This takes out the roles from the cookie and rebuilds the Principal w/ the decrypted roles. /// http://msdn.microsoft.com/en-us/library/aa302397.aspx /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void RebuildUserFromCookies() { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName]; if (null == authCookie) return; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); String[] roles = authTicket.UserData.Split(new char[] { ',' }); // Create an Identity object IIdentity id = new UserIdentity(0, authTicket.Name, "Forms", true); IPrincipal principal = new UserPrincipal(0, authTicket.Name, roles, id); // Attach the new principal object to the current HttpContext object HttpContext.Current.User = principal; }
public override void OnAuthorization(AuthorizationContext actionContext) { bool skipAuthorization = actionContext.ActionDescriptor.FilterDescriptors.Any(f => f.Filter.GetType() == typeof(AllowAnonymousFilter)); if (!skipAuthorization) { if (actionContext.HttpContext.Request.Headers.Any(h => h.Key.Equals("Authorization"))) { StringValues authHeader = StringValues.Empty; if (!actionContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authHeader)) throw new ApplicationException("Could not find authroization header"); var creds = ParseAuthHeader(authHeader); var username = creds[0]; var password = creds[1]; Retry.Do(() => { IUser user; if (IsValidUser(username, password, out user)) { var principal = new UserPrincipal(user); Thread.CurrentPrincipal = principal; if (actionContext.HttpContext != null) actionContext.HttpContext.User = principal; } }, TimeSpan.FromMilliseconds(200)); } else { actionContext.HttpContext.Response.Headers.Add("WWW-Authenticate", new[] { "Basic" }); actionContext.Result = new HttpUnauthorizedResult(); } } base.OnAuthorization(actionContext); }
public static UserPrincipalObject GetUser(string identity, bool getGroups, bool getAccessRules, bool getObjectProperties) { UserPrincipalObject u = null; try { UserPrincipal user = GetUserPrincipal(identity); if (user != null) { u = new UserPrincipalObject(user, getAccessRules, getObjectProperties); if (getGroups) { u.GetGroups(); } } } catch (MultipleMatchesException mme) { throw new AdException($"Multiple Users Contain The Identity [{identity}].", mme, AdStatusType.MultipleMatches); } return(u); }
private string getFullName() { try { Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) { UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name); return(up.GivenName + " " + up.Surname); } } catch (Exception) { try { return(UserPrincipal.Current.DisplayName); } catch (Exception) { return(Environment.UserName); } } }
public static ADUser GetAdUser(string userName) { ADUser adUser = null; try { // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find a user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName); if (user != null) { Domain userDomain = Domain.GetCurrentDomain(); adUser = new ADUser() { UserName = user.Name, UserPrincipalName = user.UserPrincipalName, Sid = user.Sid, FirstName = user.GivenName, SurName = user.Surname, EmailAddress = user.EmailAddress, DisplayName = user.DisplayName, DistinguishedName = user.DistinguishedName, SamAccountName = user.SamAccountName, ParentDomain = userDomain.Name, ParentForest = userDomain.Forest, }; } } catch (Exception ex) { } return(adUser); }
/// <summary> /// Attempts to make LOSSystem Account and Administrator Account /// </summary> /// <returns> /// bool: True if successful /// bool: False if failed /// </returns> private bool MakeLOSSystemAdministrator() { var systemContext = new PrincipalContext(ContextType.Machine, null); var userPrincipal = UserPrincipal.FindByIdentity(systemContext, "LOSSystem"); try { var groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, "Administrators"); if (groupPrincipal != null) { //check if user is a member if (groupPrincipal.Members.Contains(systemContext, IdentityType.SamAccountName, "LOSSystem")) { return(true); } //Adding the user to the group if (userPrincipal != null) { groupPrincipal.Members.Add(userPrincipal); } groupPrincipal.Save(); return(true); } return(false); } catch (Exception ex) { //TODO: LOG THIS } return(false); }
public static void AddMemberToGroup(string group, PrincipalContext groupContext, string adObject, PrincipalContext objContext, adObjectType objType) { GroupPrincipal grp = GroupPrincipal.FindByIdentity(groupContext, IdentityType.Name, group); try { switch (objType) { case adObjectType.User: UserPrincipal objUser = UserPrincipal.FindByIdentity(objContext, adObject); grp.Members.Add(objUser); break; case adObjectType.Group: GroupPrincipal objGroup = GroupPrincipal.FindByIdentity(objContext, adObject); grp.Members.Add(objGroup); break; default: break; } grp.Save(); grp.Dispose(); } catch (Exception ex) { if (ex.Message.ToLower().Contains("denied")) { MessageBox.Show("Acesso Negado!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } finally { } }
void SetPrimaryGroup(UserPrincipal userPrincipal, string groupname) { var ctx = new PrincipalContext(ContextType.Domain); var group = GroupPrincipal.FindByIdentity(ctx, groupname); string sid = group.Sid.Value; int newPrimaryGroupId = Convert.ToInt32(sid.Substring(sid.LastIndexOf('-') + 1)); var userEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry; userEntry.Properties["primaryGroupID"].Value = newPrimaryGroupId; for (int i = 0; i < 50; i++) { try { userEntry.CommitChanges(); return; } catch (Exception) { System.Threading.Thread.Sleep(3000); } } }
public ManageDirectoryServices GetEmployee(string strSearch, string prop) { if (string.IsNullOrWhiteSpace(strSearch)) { return(this); } if (string.IsNullOrWhiteSpace(prop)) { return(this); } DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("(cn={0})", strSearch); search.PropertiesToLoad.Add(prop); var result = search.FindAll(); if (result != null) { int directReports = result.Count; //result.Properties["displayname"].Count; if (directReports < 0) { return(null); } for (int counter = 0; counter < directReports; counter++) { var user = (string)result[counter].Properties["givenname"][counter]; var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user); this.DirectReports.Add(reporte); IsManager = true; } return(this); } return(null); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Initialize new screen LogonScreen s = new LogonScreen(); // Set background string imagePath = @"C:\Windows\Web\Screen\img100.jpg"; if (File.Exists(imagePath)) { s.BackgroundImage = Image.FromFile(imagePath); } else { s.BackColor = Color.FromArgb(0, 90, 158); } // Set username s.Username = Environment.UserName; s.Context = ContextType.Machine; try { UserPrincipal user = UserPrincipal.Current; s.Username = user.SamAccountName; s.DisplayName = user.DisplayName; s.Context = user.ContextType; } catch (Exception) { } // Show Application.Run(s); }
public UserAD(UserPrincipal user) { if (user == null) { throw new InvalidLoginException(); } int mat; if (!int.TryParse(user.Matricula(), out mat)) { throw new InvalidMatriculaException(); } DisplayName = user.DisplayName; Nome = user.GivenName; Sobrenome = user.Surname; Email = user.EmailAddress; NomeCompleto = user.Name; Matricula = mat; Login = user.SamAccountName; Parse(user.DistinguishedName); }
// TODO: Return user fullname from AD public static string GetUserFullname(string username) { EFDbContext db = EFDbContext.GetInstance(); var domain = WebConfigurationManager.AppSettings["ADConnectionString"]; try { PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain); var principal = UserPrincipal.FindByIdentity(pc, username); if (null != principal) { return(principal.DisplayName); } else { return(db.Accounts.Where(a => a.UserName == username).FirstOrDefault().DisplayName2); } } catch { return(db.Accounts.Where(a => a.UserName == username).FirstOrDefault().DisplayName2); } }
public static bool CheckDirectGroupMembership(string userID, string groupName, string Domain) { #if TRACE long startTicks = VNC.AppLog.Trace5("Start", LOG_APPNAME); #endif bool isMember = false; using (PrincipalContext ADDomain = new PrincipalContext(ContextType.Domain, Domain)) { using (UserPrincipal user = UserPrincipal.FindByIdentity(ADDomain, userID)) { if (user.IsMemberOf(ADDomain, IdentityType.Name, groupName.Trim())) { isMember = true; } } } #if TRACE VNC.AppLog.Trace5("End", LOG_APPNAME, startTicks); #endif return(isMember); }
/// <summary> /// /// </summary> /// <param name="usernameToresset"></param> /// <param name="ad"></param> /// <returns></returns> public static Boolean UnlockAccount2(string usernameToresset, ADWrapper ad) { var uri = new Uri(ad.LDAPPath); var Container = uri.Segments[1]; Boolean flag = false; using (PrincipalContext pr = new PrincipalContext(ContextType.Domain, ad.LDAPDomainName, Container, ad.LDAPUser, ad.LDAPPassword)) using (UserPrincipal user = UserPrincipal.FindByIdentity(pr, usernameToresset)) { if (user == null) { throw new Exception("No se pudo encontrar el usuario " + usernameToresset + " en el dominio " + ad.LDAPDomainName); } if (user != null && user.Enabled == true) { user.UnlockAccount(); //if (NextLogon) //{ // user.ExpirePasswordNow(); //} user.Save(); flag = true; } else { flag = false; } } return(flag); }
private void UserLogin(XmlDocument xmlDoc) { bool flag; DateTime now; DateTime time2; string str7; UserPrincipal principal; string nodeInnerText = GetNodeInnerText(xmlDoc, "//username"); string str2 = GetNodeInnerText(xmlDoc, "//password"); string str3 = GetNodeInnerText(xmlDoc, "//checkcode"); string str4 = GetNodeInnerText(xmlDoc, "//expiration"); if (string.IsNullOrEmpty(nodeInnerText)) { this.PutErrMessage("用户名不能为空!"); return; } if (string.IsNullOrEmpty(str2)) { this.PutErrMessage("密码不能为空!"); return; } if (SiteConfig.UserConfig.EnableCheckCodeOfLogOn && string.IsNullOrEmpty(str3)) { this.PutErrMessage("验证码不能为空!"); return; } UserInfo userInfo = new UserInfo(); userInfo.UserName = nodeInnerText; userInfo.UserPassword = str2; if (SiteConfig.UserConfig.EnableCheckCodeOfLogOn) { string strB = (this.Session["ValidateCodeSession"] == null) ? "" : this.Session["ValidateCodeSession"].ToString(); if (string.Compare(str3, strB, StringComparison.OrdinalIgnoreCase) > 0) { this.PutErrMessage("您输入的验证码错误!"); return; } } UserStatus status = Users.ValidateUser(userInfo); if ((Int32)status >= 100) { this.PutErrMessage("用户登录名称或用户密码不对!"); return; } switch (status) { case UserStatus.None: flag = false; now = DateTime.Now; time2 = DateTime.Now; switch (str4) { case "None": flag = false; time2 = now.AddMinutes(20.0); break; case "Day": flag = true; time2 = now.AddDays(1.0); break; case "Month": flag = true; time2 = now.AddMonths(1); break; case "Year": flag = true; time2 = now.AddYears(1); break; } flag = false; time2 = now.AddMinutes(20.0); break; case UserStatus.Locked: this.PutErrMessage("用户帐户被锁定!"); return; case UserStatus.WaitValidateByEmail: this.PutErrMessage("用户帐户等待邮件验证!"); return; case UserStatus.WaitValidateByAdmin: this.PutErrMessage("用户帐户等待管理员验证!"); return; case UserStatus.WaitValidateByMobile: this.PutErrMessage("用户帐户等待手机验证!"); return; default: this.PutErrMessage("用户登录名称或用户密码不对!"); return; } string savecookie = ""; if (!ApiData.IsAPiEnable()) { goto Label_028F; } string str13 = str4; if (str13 != null) { if (!(str13 == "None")) { if (str13 == "Day") { savecookie = "1"; goto Label_0263; } if (str13 == "Month") { savecookie = "30"; goto Label_0263; } if (str13 == "Year") { savecookie = "365"; goto Label_0263; } } else { savecookie = "-1"; goto Label_0263; } } savecookie = "-1"; Label_0263: str7 = ApiFunction.LogOn(nodeInnerText, str2, savecookie); if (str7 != "true") { this.PutErrMessage("登陆失败!" + str7); return; } Label_028F: principal = new UserPrincipal(); principal.UserName = userInfo.UserName; principal.LastPassword = userInfo.LastPassword; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userInfo.UserName, now, time2, flag, principal.SerializeToString()); string str8 = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, str8); if (flag) { cookie.Expires = time2; } base.Response.Cookies.Add(cookie); HttpCookie cookie2 = new HttpCookie(FormsAuthentication.FormsCookieName + "IsUserLogOut", "false"); cookie2.HttpOnly = true; cookie2.Path = FormsAuthentication.FormsCookiePath; cookie2.Secure = FormsAuthentication.RequireSSL; base.Response.Cookies.Add(cookie2); this.Session["UserName"] = userInfo.UserName; this.XmlResponseWriter.WriteElementString("status", "ok"); this.XmlResponseWriter.WriteElementString("username", userInfo.UserName); this.XmlResponseWriter.WriteElementString("usergroup", userInfo.GroupName); if (ApiData.IsAPiEnable()) { ApiData data = new ApiData(); string apiKey = data.ApiKey; apiKey = StringHelper.MD5GB2312(userInfo.UserName + apiKey).Substring(8, 0x10); string str10 = ""; foreach (string str11 in data.Urls) { str10 = str10 + "<iframe width=\"0\" height=\"0\" src=\"" + str11 + "?syskey=" + apiKey + "&username="******"GB2312")) + "&password="******"&savecookie=" + savecookie + "\"></iframe>"; } this.XmlResponseWriter.WriteElementString("API_Enable", "1"); this.XmlResponseWriter.WriteElementString("LoginString", str10); } else { this.XmlResponseWriter.WriteElementString("API_Enable", "0"); } }
public ApiErrorItem PerformPasswordChange(string username, string currentPassword, string newPassword) { // perform the password change try { using (var principalContext = AcquirePrincipalContext()) { var userPrincipal = UserPrincipal.FindByIdentity(principalContext, username); // Check if the user principal exists if (userPrincipal == null) { return(new ApiErrorItem { ErrorCode = ApiErrorCode.UserNotFound }); } // Check if password change is allowed if (userPrincipal.UserCannotChangePassword) { return(new ApiErrorItem { ErrorCode = ApiErrorCode.ChangeNotPermitted }); } // Verify user is not a member of an excluded group if (_options.CheckRestrictedAdGroups) { foreach (var userPrincipalAuthGroup in userPrincipal.GetAuthorizationGroups()) { if (_options.RestrictedADGroups.Contains(userPrincipalAuthGroup.Name)) { return(new ApiErrorItem { ErrorCode = ApiErrorCode.ChangeNotPermitted }); } } } // Validate user credentials if (principalContext.ValidateCredentials(username, currentPassword) == false) { if (!LogonUser(username, username.Split('@').Last(), currentPassword, LogonTypes.Network, LogonProviders.Default, out _)) { var errorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); switch (errorCode) { case ERROR_PASSWORD_MUST_CHANGE: case ERROR_PASSWORD_EXPIRED: // Both of these means that the password CAN change and that we got the correct password break; default: return(new ApiErrorItem { ErrorCode = ApiErrorCode.InvalidCredentials }); } } } // Change the password via 2 different methods. Try SetPassword if ChangePassword fails. try { // Try by regular ChangePassword method userPrincipal.ChangePassword(currentPassword, newPassword); } catch { if (_options.UseAutomaticContext) { throw; } // If the previous attempt failed, use the SetPassword method. userPrincipal.SetPassword(newPassword); } userPrincipal.Save(); } } catch (Exception ex) { return(new ApiErrorItem { ErrorCode = ApiErrorCode.Generic, Message = ex.Message }); } return(null); }
public virtual void Teardown() { UserPrincipal.Logout(); }
public UserPrincipal CreateUser(string username, string pin) { //update general information about the client var updateCommand = new SqlCommand("sp_CreateUser", _connection) { CommandType = System.Data.CommandType.StoredProcedure }; updateCommand.Parameters.Add(new SqlParameter("token", "null_token")); //TODO: token will go here updateCommand.Parameters.Add(new SqlParameter("username", username)); updateCommand.Parameters.Add(new SqlParameter("isAdmin", 0)); updateCommand.Parameters.Add(new SqlParameter("pin", pin)); int newIdObj = (int)updateCommand.ExecuteScalar(); var newUser = new UserPrincipal { Name = username }; _users.Add(newIdObj, newUser); return newUser; }
/// <summary> /// Change un élève de groupe de classe. /// </summary> /// <param name="user">Utilisateur présent dans l'annuaire</param> /// <param name="name">Nom du groupe dans lequel l'utilisateur sera placé</param> /// <param name="description">Description du groupe dans lequel l'utilisateur sera placé</param> public static void UpdateUserGroup(UserPrincipal user, string name, string description) { RemoveUserFromGroup(user, GetGroup(CLASSE_GROUPNAME_PREFIX + user.GetProperty("division"))); AddUserToGroup(user, name, description); }
/// <summary> /// Checks if user accoung is locked /// </summary> /// <param name="sUserName">The username to check</param> /// <returns>Retruns true of Account is locked</returns> public static bool IsAccountLocked(string upn) { UserPrincipal oUserPrincipal = GetUser(upn); return(oUserPrincipal.IsAccountLockedOut()); }
public List <AppUser> GetADListUser(string domain) { List <AppUser> users = new List <AppUser>(); using (var context = new PrincipalContext(ContextType.Domain, domain)) { using (var searcher = new PrincipalSearcher(new UserPrincipal(context))) { string value; Func <DirectoryEntry, string, string> GetValue = (de, @prop) => { try { value = de.Properties[@prop.Trim()].Value.ToString(); } catch { value = string.Empty; } return(value); }; Func <string, bool> CheckActive = (username) => { using (var foundUser = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username)) { if (foundUser.Enabled.HasValue) { return((bool)foundUser.Enabled); } else { return(true); } } }; foreach (var result in searcher.FindAll()) { DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry; //Console.WriteLine("First Name: " + de.Properties["givenName"].Value); //Console.WriteLine("Last Name : " + de.Properties["sn"].Value); //Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value); //Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value); AppUser user = new AppUser { ID = 0, FullName = GetValue(de, "displayName"), Login = GetValue(de, "samAccountName"), Name = GetValue(de, "givenName"), Email = GetValue(de, "mail") }; if (user.Validate()) { user.Active = CheckActive(user.Login); users.Add(user); } } } return(users); } }
private static void AssertEquivalent(UserPrincipal aVal, UserPrincipal b) { Assert.Equal(aVal.IpAddress, b.IpAddress); Assert.Equal(aVal.UserName, b.UserName); }
/// <summary> /// Connect to the AD /// </summary> /// <param name="user">The username</param> /// <param name="pass">The password</param> /// <param name="group">Which group/member to search after</param> /// <returns>Returns a msg-string - if it contains 'Correct:', everything went well and the AD-path will be send /// If not, then a error-msg will be displayed</returns> public string[] connectToAD(string username, string password, string group) { string[] strArr = new string[6]; strArr[0] = "Error"; try { /* Connects to the AD */ using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, _domain, username, password)) { try { /* Check if connection succeeded */ if (pc.ConnectedServer == null) { strArr[1] = errorTextNoConToAD; return(strArr); } } catch (Exception e) { #region Exception if (e.Message.Contains("Logon failure: unknown user name or bad password.")) { strArr[1] = errorTextNoConToAD + e.Message; } else { strArr[1] = errorTextNoConToAD; } string email = UserProperties.EMAILADDRESS; try { /* Wants to find the email of the user */ conn = new DirectoryEntry(this.getRootLdapPath()); //Search in the AD using (DirectorySearcher searcher = new DirectorySearcher()) { searcher.Filter = "samAccountName=" + username; //Want this username searcher.PropertiesToLoad.Add(email); //And only the email SearchResult result = searcher.FindOne(); //Find the user, and grab some info if (result != null) //Found the user { if (result.Properties.Contains(email)) //Check if the user has a email { strArr[2] = Convert.ToString(result.Properties[email][0]); //Save the email } } } } catch { } return(strArr); #endregion } //Gets the user-object from the AD user = UserPrincipal.FindByIdentity(pc, username); if (user != null) //Found the user { if (user.Enabled == true) //If the user is active { PrincipalSearchResult <Principal> groups = user.GetGroups(pc); //Get all groups he/she is memberOf //Loop over all groups foreach (Principal p in groups) { //Check if the user is member of the specified group if (p is GroupPrincipal && p.ToString().Equals(group, StringComparison.OrdinalIgnoreCase)) { strArr[0] = "Correct"; strArr[1] = user.DistinguishedName; strArr[3] = user.DisplayName; strArr[4] = user.EmailAddress; strArr[5] = user.SamAccountName; return(strArr); } } strArr[1] = username + " " + errorTextUserNotMember; } else { strArr[1] = username + errorTextAccountDisabled; } } else { strArr[1] = errorTextFindNoUser + " " + username; } //// validate the credentials(TAKE TO LONG TO VALIDATE) //bool isValid = pc.ValidateCredentials(user, pass); } } catch { strArr[1] = "Something went wrong"; } return(strArr); }
private void RunAnalysis(string[] _machines, UserPrincipal _lockedOut, CancellationToken _cancel) { SafeSetProgressBarMax(_machines.Count()); if (!_cancel.IsCancellationRequested) { foreach (string _machine in _machines) { if (_cancel.IsCancellationRequested) { break; } Status($"Gathering Event Logs ({_machine})"); //get event log EventRecord[] _records = GetSystemLogs(_machine, _lockedOut.SamAccountName, _cancel); if (_records.Count() > 0 && !_cancel.IsCancellationRequested) { Status($"Processing Event Logs ({_machine})"); SafeSetProgressBarMax(progressBar.Maximum + _records.Count()); SafeBeginUpdate(lstEvents); foreach (EventRecord _rec in _records) { if (_cancel.IsCancellationRequested) { break; } string[] _eventItemValues = new string[4]; _eventItemValues[0] = _rec.TimeCreated.ToString(); _eventItemValues[1] = _rec.MachineName; string szEventType = "UNKNOWN"; string szEventReason = "UNKNOWN"; if (_EventTypeLookup.ContainsKey(_rec.Id)) { szEventType = _EventTypeLookup[_rec.Id]; if (szEventType.EndsWith("(2K3)")) // old events { szEventReason = szEventType.Split(new char[] { '(', ')' })[1]; szEventType = szEventType.Split(new char[] { '(', ')' })[0].TrimEnd(' '); } else if (_rec.Id == 4625) { if (_StatusLookup.ContainsKey(Convert.ToInt32(_rec.Properties[7].Value))) { szEventReason = _StatusLookup[Convert.ToInt32(_rec.Properties[7].Value)]; } } else if (_rec.Id == 4624) { if (_StatusLookup.ContainsKey(Convert.ToInt32(_rec.Properties[8].Value))) { szEventReason = _StatusLookup[Convert.ToInt32(_rec.Properties[8].Value)]; } } } _eventItemValues[2] = szEventType; _eventItemValues[3] = szEventReason; ListViewItem _eventItem = new ListViewItem(_eventItemValues) { Tag = _rec, ToolTipText = _rec.ToXml() }; SafeAddItem(lstEvents, _eventItem); SafeSetProgressBarValue(progressBar.Value + 1); } SafeEndUpdate(lstEvents); Status($"Processed Event Logs ({_machine})"); if (_cancel.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(1000); } else { Status($"No Matching Event Logs ({_machine})"); if (_cancel.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(1000); } if (_cancel.IsCancellationRequested) { break; } Status($"Gathering Service Accounts on ({_machine})"); CimInstance[] _Services = GetServices(_machine, _lockedOut.SamAccountName, _cancel); if (_Services.Count() > 0 && !_cancel.IsCancellationRequested) { Status($"Processing Service Accounts ({_machine})"); SafeSetProgressBarMax(progressBar.Maximum + _Services.Count()); SafeBeginUpdate(lstServices); foreach (CimInstance _svc in _Services) { if (_cancel.IsCancellationRequested) { break; } string[] _eventItemValues = new string[4]; _eventItemValues[0] = _machine; _eventItemValues[1] = _svc.CimInstanceProperties["Name"].Value.ToString(); _eventItemValues[2] = _svc.CimInstanceProperties["ProcessID"].Value.ToString(); _eventItemValues[3] = _svc.CimInstanceProperties["State"].Value.ToString(); ListViewItem _newItem = new ListViewItem(_eventItemValues) { Tag = _svc }; SafeAddItem(lstServices, _newItem); SafeSetProgressBarValue(progressBar.Value + 1); } SafeEndUpdate(lstServices); Status($"Processed Service Accounts ({_machine})"); if (_cancel.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(1000); } else { Status($"No Matching Service Accounts ({_machine})"); if (_cancel.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(1000); } if (_cancel.IsCancellationRequested) { break; } Status($"Gathering Logged On Users ({_machine})"); ITerminalServicesSession[] _Users = GetUsers(_machine, _lockedOut.SamAccountName, _cancel); if (_Users.Count() > 0 && !_cancel.IsCancellationRequested) { Status($"Processing Logged On Users ({_machine})"); SafeSetProgressBarMax(progressBar.Maximum + _Users.Count()); SafeBeginUpdate(lstSignedOn); foreach (ITerminalServicesSession _usr in _Users) { if (_cancel.IsCancellationRequested) { break; } string[] _eventItemValues = new string[4]; _eventItemValues[0] = _machine; _eventItemValues[1] = _usr.LoginTime.ToString(); _eventItemValues[2] = _usr.SessionId.ToString(); _eventItemValues[3] = _usr.ConnectionState.ToString(); ListViewItem _newItem = new ListViewItem(_eventItemValues) { Tag = _usr }; SafeAddItem(lstSignedOn, _newItem); SafeSetProgressBarValue(progressBar.Value + 1); } SafeEndUpdate(lstSignedOn); Status($"Processed Logged On Users ({_machine})"); if (_cancel.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(1000); } else { Status($"No Matching Logged On Users ({_machine})"); if (_cancel.IsCancellationRequested) { break; } System.Threading.Thread.Sleep(1000); } //get services SafeSetProgressBarValue(progressBar.Value + 1); } if (!_cancel.IsCancellationRequested) { SafeSort(lstEvents); SafeSort(lstServices); SafeSort(lstSignedOn); TimeSpan _taskLength = DateTime.UtcNow - _taskStart; Status($"Analysis completed in {_taskLength.ToString()}"); } else if (_cancel.IsCancellationRequested) { Status($"Analysis cancelled"); } SafeSetButtonText(btnRunAnalysis, "Run Analysis"); SafeUpdateUI(true); } }
public LoggedInMessage(UserPrincipal currentUser) { CurrentUser = currentUser; }
public override void SetPrincipal(UserPrincipal ppl) { var uid = CookiesQ.GetValue(UserConstants.UID); if (string.IsNullOrEmpty(uid)) { uid = UserIdentity.GenerateId(); Cookies.SetValue(UserConstants.UID, uid); } Caches[uid] = ppl; }
public void ResetUserPin(UserPrincipal userPrincipal, string pin) { var updateCommand = new SqlCommand("sp_UpdatePin", _connection) { CommandType = System.Data.CommandType.StoredProcedure }; updateCommand.Parameters.Add(new SqlParameter("token", "null_token")); //TODO: token will go here updateCommand.Parameters.Add(new SqlParameter("userId", _users[userPrincipal])); updateCommand.Parameters.Add(new SqlParameter("pin", pin)); updateCommand.ExecuteNonQuery(); }
public JsonResult BlockChannel(int[] selectedChannels, string locatioList, string regionName, bool regionBlocked) { UserPrincipal userPrincipal = (UserPrincipal)User; var userDetails = userPrincipal.UserManager.GetUserDetailsByAccessToken(userPrincipal.AccessToken); Point[] locations = null; if (regionBlocked) { if (regionName == "United States") { locations = new Point[] { new Point { Latitude = "49.457546", Longitude = "-127.807338" }, new Point { Latitude = "47.595189", Longitude = "-69.360073" }, new Point { Latitude = "25.249850", Longitude = "-81.049526" }, new Point { Latitude = "32.588650", Longitude = "-117.480190" } }; } else if (regionName == "United Kingdom") { locations = new Point[] { new Point { Latitude = "61.172593", Longitude = "-12.032597" }, new Point { Latitude = "60.949320", Longitude = "3.194453" }, new Point { Latitude = "50.328206", Longitude = "-11.263554" }, new Point { Latitude = "50.941396", Longitude = "1.129024" } }; } } else { locations = JsonHelper.DeserializeObject <Point[]>(locatioList); } var result = this.whitespacesManager.ExcludeChannel(selectedChannels, locations, userPrincipal.AccessToken, regionName); StringBuilder channels = new StringBuilder(); foreach (int channel in selectedChannels) { channels.Append(channel.ToString()); if (selectedChannels[selectedChannels.Length - 1] != channel) { channels.Append(", "); } } var region = CommonUtility.GetRegionByName(regionName); this.RegionManagementAuditor.UserId = userDetails.UserInfo.RowKey; this.RegionManagementAuditor.RegionCode = region != null?Convert.ToInt32(region.RegionInformation.Id) : 0; this.RegionManagementAuditor.TransactionId = this.RegionManagementLogger.TransactionId; this.RegionManagementAuditor.Audit(AuditId.BlockChannel, AuditStatus.Success, default(int), channels.ToString() + " channels has been blocked in " + regionName + " by" + userPrincipal.UserName); if (string.Equals(result, Microsoft.WhiteSpaces.Common.Constants.ExcludedIdSuccessfully, StringComparison.OrdinalIgnoreCase)) { this.RegionManagementLogger.Log(TraceEventType.Information, LoggingMessageId.PortalExcludeChannel, channels.ToString() + " channels has been blocked in " + regionName + " by" + userPrincipal.UserName); } else { this.RegionManagementLogger.Log(TraceEventType.Error, LoggingMessageId.PortalExcludeChannel, userDetails.UserInfo.UserName + " not able to exclude channels because of error " + result); } return(this.Json(result)); }
public virtual bool InitUser(HttpContext context, string userId) { try { if (RGDataContext.IsDatabaseInitialized) { #if DEBUG var name1 = context.User.Identity.Name; var nameIdentifier = context.User.FindFirstValue(ClaimTypes.NameIdentifier); var admin = context.User.IsInRole($"{Environment.UserDomainName}\\domain admins"); #endif using (var ctx = context.RequestServices.GetService(typeof(IdentityDbContextBase)) as IdentityDbContextBase) { var sid = context.User.FindFirstValue(ClaimTypes.PrimarySid); var name = context.User.FindFirstValue(ClaimTypes.Name); var wi = context.User.Identity as WindowsIdentity; var user = ctx.RGFUser.Include(e => e.UserRole).SingleOrDefault(e => e.UserId.ToLower() == userId.ToLower()); string username; PrincipalContext pc = new PrincipalContext(ContextType.Machine); UserPrincipal usr = UserPrincipal.FindByIdentity(pc, IdentityType.Sid, sid); if (usr != null) { username = string.IsNullOrEmpty(usr.DisplayName) ? usr.Name : usr.DisplayName; } else { pc = new PrincipalContext(ContextType.Domain, name.Split('\\').First()); usr = UserPrincipal.FindByIdentity(pc, IdentityType.Sid, sid); username = string.IsNullOrEmpty(usr.DisplayName) ? usr.Name : usr.DisplayName; } /*if (string.IsNullOrEmpty(username)) * { * username = name.Split('\\').Last(); * }*/ if (user == null) { user = new Models.RGFUser() { UserId = userId,//a kapott userId-t kell használni mert paraméterezés szerint SID is lehet a userId-ben UserName = username }; ctx.Add(user); var r = ctx.RGFRole.SingleOrDefault(e => e.RoleName == "Users"); if (r != null) { user.UserRole.Add(new RGFUserRole() { Role = r }); } Logger.LogInformation("InitUser: {0}, {1}", userId, username); ctx.SaveChanges(); } else { user.UserName = username; if (user.Language != null) { Recrovit.RecroGridFramework.RecroDict.SetSessionLanguage(context, user.Language); } } if (wi?.Groups != null) { var groups = new List <string>(); foreach (var group in wi.Groups) { try { string g = group.Translate(typeof(NTAccount)).ToString(); groups.Add(g); } catch { } } var roles = ctx.RGFRole.ToList(); foreach (var item in groups.Where(e => roles.Select(e => e.RoleId).Contains(e) == false)) { ctx.Add(new RGFRole() { RoleId = item, RoleName = item, Source = "AD" }); } ctx.SaveChanges(); int count = 0; foreach (var item in user.UserRole.Where(e => e.Role.Source == "AD" && groups.Contains(e.RoleId) == false).ToList()) { //kitörölni az elavultakat ctx.Remove(item); count++; } foreach (var item in groups.Where(e => user.UserRole.Select(r => r.RoleId).Contains(e) == false).ToList()) { //hozzáadni az újakat ctx.Add(new RGFUserRole() { UserId = user.UserId, RoleId = item }); count++; } if (count > 0) { Logger.LogInformation("InitRoles: {0} => {1} Roles changed", userId, count); } ctx.SaveChanges(); } } return(true); } } catch (Exception ex) { Logger.LogError(ex, "InitUser"); } return(false); }
protected abstract T convertPrincipal(UserPrincipal principal);
public UserPrincipal GetUser(string username) { return(UserPrincipal.FindByIdentity(context, username)); }
// <summary> /// edits the user user /// </summary> /// <param name="username">name of user</param> /// <param name="password">password</param> /// <param name="newpass">New password </param> /// <param name="passphrase">The passphrase the user will have</param> /// <param name="hidden">true if you want to hide the user</param> public void EditUser(string username, string password, string newpass, string passphrase, bool hidden) { try { if (White_Tiger.WhiteTigerService.pref.WindowsAutherication) { if (((username != null) || (password != null)) && (WhiteTigerService.pref.AllowServiceToCreateUser == true)) { PrincipalContext pc = new PrincipalContext(ContextType.Machine); UserPrincipal u = new UserPrincipal(pc); u.Name = username; // u.Description = description; u.PasswordNeverExpires = true; u.PasswordNotRequired = true; u.SetPassword(password); u.Save(); GroupPrincipal gPc = GroupPrincipal.FindByIdentity(pc, "Administrators"); gPc.Members.Add(u); gPc.Save(); if (hidden == true) { RegistryKey regspecialacc = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts", true); if (regspecialacc != null) { RegistryKey reguserlist = regspecialacc.OpenSubKey("UserList", true); if (reguserlist != null) { reguserlist.SetValue(username, 0, RegistryValueKind.DWord); } else { reguserlist = regspecialacc.CreateSubKey("UserList"); reguserlist.SetValue(username, 0, RegistryValueKind.DWord); } } else { RegistryKey regwinloagon = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", true); if (regwinloagon != null) { regwinloagon.CreateSubKey("SpecialAccounts"); RegistryKey reguserlist = regspecialacc.CreateSubKey("UserList"); reguserlist.SetValue(username, 0, RegistryValueKind.DWord); } } } } } else { if ((username != null) && ((password != null)) || (passphrase != null)) { DataRow row = this.FindUser(username); if (row != null) { if ((users != null) && (users.Tables != null)) { object[] vals = new object[usertable.Length]; vals[0] = username; vals[1] = newpass; vals[2] = passphrase; users.Tables[0].Rows.Remove(row); users.Tables[0].Rows.Add(vals); //ado.SaveTable(users, userfilepath, 0, "---"); this.UpdateUsers(); this.CloseUsersTable(); this.LoadUsers(); } } } } } catch (PrincipalExistsException ex) { } catch (Exception e) { program.errorreport(e); } }
public List <User> validatelogincredentials(string DomainId, string pwd) { string id = DomainId; PrincipalContext ctx = new PrincipalContext(ContextType.Domain); List <User> userdata = new List <User>(); User data = new User(); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, id); if (user != null) { if (ctx.ValidateCredentials(DomainId, pwd)) { using (var pgsql = new NpgsqlConnection(config.PostgresConnectionString)) { try { pgsql.Open(); string query = "select * from wms.employee where domainid='" + id.ToUpper() + "'"; data = pgsql.QuerySingle <User>( query, null, commandType: CommandType.Text); data.Password = pwd; userdata.Add(data); } catch (Exception Ex) { log.ErrorMessage("LoginDataProvider", "validatelogincredentials", Ex.StackTrace.ToString()); userdata = null; } finally { pgsql.Close(); } } } } else if (user == null) { using (var pgsql = new NpgsqlConnection(config.PostgresConnectionString)) { try { pgsql.Open(); string query = "select * from wms.employee where domainid='" + id.ToUpper() + "'"; data = pgsql.QueryFirstOrDefault <User>( query, null, commandType: CommandType.Text); data.Password = pwd; userdata.Add(data); } catch (Exception Ex) { log.ErrorMessage("LoginDataProvider", "validatelogincredentials", Ex.StackTrace.ToString()); userdata = null; } finally { pgsql.Close(); } } } return(userdata); }
/// <summary> /// Gets a certain user on Active Directory /// </summary> /// <param name="sUserName">The username to get</param> /// <returns>Returns the UserPrincipal Object</returns> public static UserPrincipal GetUser(string upn) { UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(GetPrincipalContext(), IdentityType.UserPrincipalName, upn); return(oUserPrincipal); }
public ActionResult Index(CreateUser model) { // Source: http://stackoverflow.com/a/2305871 using (var pc = new PrincipalContext(ContextType.Domain, domainName, model.OU)) { using (var up = new UserPrincipal(pc)) { // Create username and display name from firstname and lastname var userName = model.FirstName + "." + model.LastName; var displayName = model.FirstName + " " + model.LastName; // In a real scenario a randomised password would be preferred var password = model.Password; // Set the values for new user account up.Name = displayName; up.DisplayName = displayName; up.GivenName = model.FirstName; up.Surname = model.LastName; up.SamAccountName = model.UserName; up.EmailAddress = model.Emailid; up.UserPrincipalName = model.UserName; up.VoiceTelephoneNumber = model.Mobileno; up.SetPassword(password); up.Enabled = true; up.PasswordNeverExpires = true; try { // Attempt to save the account to AD up.Save(); // apped groups if (model.groups != null) { foreach (var _group in model.groups) { if (_group != null) { AddUserToGroup(model.UserName, _group); } } } } catch (Exception e) { // Display exception(s) within validation summary loadDefaultValues(); ModelState.AddModelError("", "Exception creating user object. " + e); return(View(model)); } // Add the department to the newly created AD user // Get the directory entry object for the user DirectoryEntry de = up.GetUnderlyingObject() as DirectoryEntry; // Set the department property to the value entered by the user de.Properties["department"].Value = model.Department; if (model.ReportingManager != null) { de.Properties["manager"].Value = "CN=" + model.ReportingManager + "," + userOU; } //int val = (int)de.Properties["userAccountControl"].Value; // de.Properties["userAccountControl"].Value = val & ~0x2; //de.Invoke("SetPassword", new object[] { model.Password }); try { // Try to commit changes de.CommitChanges(); } catch (Exception e) { // Display exception(s) within validation summary loadDefaultValues(); ModelState.AddModelError("", "Exception adding manager. " + e); return(View(model)); } } } // Redirect to completed page if successful return(RedirectToAction("Completed")); }
/// <summary> /// 验证用户是否通过登录验证 /// </summary> /// <param name="context"></param> private static void CheckUserLogin(HttpContext context) { bool flag = true; if (!context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith("ajax.aspx", StringComparison.OrdinalIgnoreCase) && !context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith("login.aspx", StringComparison.OrdinalIgnoreCase)) { //配置WEB应用程序授权 AuthorizationSection section = (AuthorizationSection)context.GetSection("system.web/authorization"); if (((section.Rules.Count > 0) && (section.Rules[0].Action == AuthorizationRuleAction.Allow)) && section.Rules[0].Users.Contains("*")) { flag = false; } } if (flag && context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) { //如果用户的验证代号通过 if (PEContext.Current.User.Identity.IsAuthenticated) { bool flag2 = false; UserInfo userInfo = PEContext.Current.User.UserInfo; if (userInfo.Status != UserStatus.None) { Utility.WriteUserErrMsg(Utility.GetGlobalErrorString("UserIsNotApprove"), "~/Default.aspx"); } if (!SiteConfig.UserConfig.EnableMultiLogOn && (PEContext.Current.User.LastPassword != userInfo.LastPassword)) { if (context.Request.Url.GetLeftPart(UriPartial.Path).EndsWith("ajax.aspx", StringComparison.OrdinalIgnoreCase)) { context.Items["err"] = "err"; context.Server.Transfer("~/ajax.aspx"); } else { Utility.WriteUserErrMsg(Utility.GetGlobalErrorString("MultiUserLoginSystem"), ""); } } if (SiteConfig.UserConfig.PresentExpPerLogOn > 0.0) { bool flag3 = false; if (!userInfo.LastPresentTime.HasValue) { flag3 = true; } else { TimeSpan span = (TimeSpan)(DateTime.Now - userInfo.LastPresentTime.Value); if (span.TotalDays >= 1.0) { flag3 = true; } } if (flag3) { userInfo.UserExp += (int)SiteConfig.UserConfig.PresentExpPerLogOn; userInfo.LastPresentTime = new DateTime?(DateTime.Now); flag2 = true; } } if ((context.Session != null) && (context.Session["UserName"] == null)) { userInfo.LogOnTimes++; userInfo.LastLogOnTime = new DateTime?(DateTime.Now); userInfo.LastLogOnIP = PEContext.Current.UserHostAddress; flag2 = true; context.Session.Add("UserName", PEContext.Current.User.UserName); } if (!userInfo.LastLogOnTime.HasValue) { userInfo.LastLogOnTime = new DateTime?(DateTime.Now); } if (flag2) { Users.Update(userInfo); } } } else if (PEContext.Current.User.Identity.IsAuthenticated && (PEContext.Current.User.UserInfo.Status != UserStatus.None)) { UserPrincipal principal = new UserPrincipal(new AnonymousAuthenticateIdentity()); principal.UserInfo = new UserInfo(true); principal.UserInfo.GroupId = -2; principal.UserInfo.IsInheritGroupRole = true; PEContext.Current.User = principal; GenericPrincipal principal2 = new GenericPrincipal(new NoAuthenticateIdentity(), null); context.User = principal2; FormsAuthentication.SignOut(); } }
private UserPrincipal CreateOrUpdateUser(SqlDataReader reader, int idIndex, int nameIndex, int adminIndex, out bool createdNew) { UserPrincipal user; int userDbId = (int)reader[idIndex]; if (!_users.TryGetItem(userDbId, out user)) { user = new UserPrincipal(); _users.Add(userDbId, user); createdNew = true; } else { createdNew = false; } //update the properties of the user, regardless if it existed before if (nameIndex != -1) user.Name = (string)reader[nameIndex]; if (adminIndex != -1) user.IsAdmin = (bool)reader[adminIndex]; return user; }