public static void AuthenticateRequestDecryptCustomFormsAuthenticationTicket(HttpContext httpContext) { UserData userData; string formsCookieName = FormsAuthentication.FormsCookieName; HttpCookie httpCookie = httpContext.Request.Cookies[ string.IsNullOrWhiteSpace(formsCookieName) ? Guid.NewGuid().ToString() : formsCookieName]; if (httpCookie == null) { userData = new UserData(); } else { FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(httpCookie.Value); if (!UserData.TryParse(authenticationTicket.UserData, out userData)) { // No name will mean the Idenity has no name .. which means the user is NOT authenticated. Nice. userData = new UserData(); } } var principal = new CustomPrincipal(new CustomIdentity(userData.Id, userData.DisplayName), null); httpContext.User = principal; Thread.CurrentPrincipal = principal; }
private IPrincipal CreatePrincipal(User user) { CustomPrincipal ret = new CustomPrincipal(user.Email); ret.Id = user.Id; ret.Name = user.Name; ret.Email = user.Email; return ret; }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.IsAdmin = serializeModel.IsAdmin; HttpContext.Current.User = newUser; } }
protected void Application_PostAuthenticateRequest( Object sender, EventArgs e ) { if( HttpContext.Current.User.Identity.IsAuthenticated ) { ApplicationUser user = UserManager.FindByName( HttpContext.Current.User.Identity.Name ); CustomPrincipal newUser = new CustomPrincipal( user ); //newUser.Identity = User.Identity; //Claim cPatient = new Claim(typeof(PatientPortalPrincipal).ToString(), ); HttpContext.Current.User = newUser; } }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { string name = String.Empty; HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); name = authTicket.Name; } var identity = new CustomIdentity(name, "Forms"); var principal = new CustomPrincipal(identity); Context.User = principal; }
public void New_Test() { var user = new User(); var identity = new CustomIdentity<User>(user, user.Name, true); var roleProvider = new BasicRoleProvider<User>(); var principal = new CustomPrincipal<User>(identity, roleProvider); Assert.AreSame(identity, principal.Identity); Assert.AreSame(roleProvider, principal.RoleProvider); Assert.IsTrue(principal.IsInRole("any string")); Assert.Throws<ArgumentNullException>(() => new CustomPrincipal<User>(null, roleProvider)); Assert.Throws<ArgumentNullException>(() => new CustomPrincipal<User>(identity, null)); }
public static void Attach(IIdentity user, string applicationName, IUserManager userManager, bool cacheRoles) { Debug.Assert(user.IsAuthenticated); IPrincipal _customPrincipal = new CustomPrincipal(user, applicationName, userManager, cacheRoles); //Make sure all future threads in this app domain use this principal //but because default principal cannot be set twice: if (m_ThreadPolicySet == false) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.SetThreadPrincipal(_customPrincipal); m_ThreadPolicySet = true; } }
// Reference: http://nerddinnerbook.s3.amazonaws.com/Part12.htm // Yes .. Nerd Dinner to the rescue! and we come full circle... public static void SetUpControllerContext(ControllerBase controller, string userId = null, string displayName = null, string[] roles = null) { Condition.Requires(controller); // Some fake Authentication stuff. var customIdentity = new CustomIdentity(userId, displayName); var customPrincipal = new CustomPrincipal(customIdentity, roles); var mockControllerContext = new Mock<ControllerContext>(); mockControllerContext.Setup(x => x.HttpContext.User).Returns(customPrincipal); controller.ControllerContext = mockControllerContext.Object; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { CustomPrincipal prinzipal = new CustomPrincipal(filterContext.HttpContext.User.Identity); if (prinzipal.IsInRole(Role)) { return; } RouteValueDictionary dictionary = new RouteValueDictionary { {"controller", "Content"}, {"action", "Show"}, {"id", "AccessDenied"} }; filterContext.Result = new RedirectToRouteResult(dictionary); }
public NavigationViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IRepository repository) : base(regionManager, eventAggregator, repository) { NavigateCommand = new DelegateCommand <NavigationItem>(Navigate); AdminNavigationItems = new ObservableCollection <NavigationItem> { new NavigationItem() { Name = "Заказы", MasterView = "OrdersView", DetailsView = "OrderDetailsView" }, new NavigationItem() { Name = "Клиенты", MasterView = "ClientsView", DetailsView = "ClientDetailsView" }, new NavigationItem() { Name = "Компании", MasterView = "CompaniesView", DetailsView = "CompanyDetailsView" } }; UserNavigationItems = new ObservableCollection <NavigationItem> { new NavigationItem() { Name = "Мои заказы", MasterView = "UserOrdersView", DetailsView = "" } }; CustomPrincipal customPrincipal = Thread.CurrentPrincipal as CustomPrincipal; switch (customPrincipal.Identity.Role.Name) { case "Администратор": regionManager.RequestNavigate("MasterRegion", "OrdersView"); regionManager.RequestNavigate("DetailsRegion", "OrderDetailsView"); break; case "Пользователь": regionManager.RequestNavigate("MasterRegion", "UserOrdersView"); regionManager.RequestNavigate("DetailsRegion", "UserOrderDetailsView"); break; } SelectedItem = NavigationItems.FirstOrDefault(); }
protected override void OnStartup(StartupEventArgs e) { //Create a custom principal with an anonymous identity at startup //CustomPrincipal customPrincipal = new CustomPrincipal(); //AppDomain.CurrentDomain.SetThreadPrincipal(customPrincipal); CustomPrincipal customPrincipal = new CustomPrincipal(); AppDomain.CurrentDomain.SetThreadPrincipal(customPrincipal); base.OnStartup(e); MainWindow app = new DinnergeddonUI.Views.MainWindow(); //Show the login view MainWindowViewModel context = new MainWindowViewModel(); app.DataContext = context; app.Show(); }
private void Logout(object parameter) { Window dashboard = parameter as Window; CustomPrincipal customPrincipal = Thread.CurrentPrincipal as CustomPrincipal; if (customPrincipal != null) { customPrincipal.Identity = new AnonymousIdentity(); NotifyPropertyChanged("AuthenticatedUser"); NotifyPropertyChanged("IsAuthenticated"); // _loginCommand.RaiseCanExecuteChanged(); _logoutCommand.RaiseCanExecuteChanged(); dashboard.Close(); //MainWindow mw = new MainWindow(); //mw.Show(); } }
public static List <CMSMenuModel> MapUsers(List <tbl_AdminUsers> users, CustomPrincipal currentUser) { return(new List <CMSMenuModel> { new CMSMenuModel { Title = "Users", MenuItems = users.Select(user => new CMSMenuItem { MenuItemID = user.AdminUserID, Title = String.Format("<b>{0}: {1}</b> ({2})", user.US_UserName, user.US_Email, user.tbl_UserGroups.UG_Type), IsDelete = currentUser.HasPermission(Permission.DeleteUser), IsEdit = currentUser.HasPermission(Permission.EditUser) }).ToList() } }); }
private void BindGrid(CustomPrincipal user) { var edit = Edit; if (user.IsInRole("manager") || user.IsInRole("teacher")) { var aId = Request.QueryString["aId"]; var academicId = 0; try { academicId = Convert.ToInt32(aId); } catch { } using (var helper = new DbHelper.AcademicYear()) { //var aca = helper.ListAcademicYears(user.SchoolId); var aca = helper.GetCurrentPreviousAndNextAcademicYears(user.SchoolId, academicId); if (aca[0] != null) { lnkPrevious.NavigateUrl = "~/Views/Academy/?aId=" + aca[0].Id; } else { lnkPrevious.Visible = false; } if (aca[2] != null) { lnkNext.NavigateUrl = "~/Views/Academy/?aId=" + aca[2].Id; } else { lnkNext.Visible = false; } //foreach (var ay in aca) if (aca[1] != null) { var ay = aca[1]; var uc = (UserControls.AcademicYearListUC) Page.LoadControl("~/Views/Academy/UserControls/AcademicYearListUC.ascx"); uc.LoadAcademicYear(ay, edit); pnlAcademicYearListing.Controls.Add(uc); } } } }
private void HRAuthenticateRequest(object objSender, EventArgs objEventArgs) { //首先获取用户登陆信息 HttpApplication app = (HttpApplication)objSender; CustomPrincipal.TrySetUserInfo(app.Context); if (!IsBypass(app) && (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)) { //HttpContext.Current.Response.Redirect("/Common/RedirectToLogin?Msg=" + Common.Access_Denied, true); } else { } }
/// <summary> /// Loguje uzytkownika w aplikacji. /// </summary> /// <param name="context">Kontekst bazy danych.</param> /// <param name="username">Nazwa użytkownika.</param> /// <param name="password">Hasło użytkownika.</param> /// <returns>SignInResult dla usera, jeśli wszystko przebiegło poprawnie, w przeciwnym razie null.</returns> public SignInResult SignIn(IUsersContext context, string username, string password) { CustomIdentity identity = _authenticationService.AuthenticateUser(context, username, password); if (identity != null) { var user = new CustomPrincipal(username); var token = GetToken(); while (!SignedInUsers.TryAdd(token, user)) //trzeba wygenerować unikalny token { token = GetToken(); } return(new SignInResult(user, token)); } return(null); }
protected override void OnStartup(StartupEventArgs e) { Log = new FuelLevelSystem.Logger.Logger(typeof(App)); Log.LogInfoMessage("App Start!!"); //Create a custom principal with an anonymous identity at startup CustomPrincipal customPrincipal = new CustomPrincipal(); AppDomain.CurrentDomain.SetThreadPrincipal(customPrincipal); base.OnStartup(e); //Show the login view //AuthenticationViewModel viewModel = new AuthenticationViewModel(new AuthenticationService()); //IView loginWindow = new LoginWindow(viewModel); //loginWindow.ShowDialog(); }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies["Cookie1"]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); var serializeModel = JsonConvert.DeserializeObject <CustomSerializeModel>(authTicket.UserData); CustomPrincipal principal = new CustomPrincipal(authTicket.Name); principal.UserId = serializeModel.UserId; principal.FirstName = serializeModel.FirstName; principal.LastName = serializeModel.LastName; principal.Roles = serializeModel.RoleName.ToArray <string>(); HttpContext.Current.User = principal; } }
// Reference: http://nerddinnerbook.s3.amazonaws.com/Part12.htm // Yes .. Nerd Dinner to the rescue! and we come full circle... public static void SetUpControllerContext(ControllerBase controller, string userId = null, string displayName = null, string[] roles = null) { Condition.Requires(controller); // Some fake Authentication stuff. var customIdentity = new CustomIdentity(userId, displayName); var customPrincipal = new CustomPrincipal(customIdentity, roles); var mockControllerContext = new Mock <ControllerContext>(); mockControllerContext.Setup(x => x.HttpContext.User).Returns(customPrincipal); controller.ControllerContext = mockControllerContext.Object; }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); CustomPrincipalSerializedModel serializeModel = serializer.Deserialize <CustomPrincipalSerializedModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.Id = serializeModel.Id; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; newUser.Role = serializeModel.Role; HttpContext.Current.User = newUser; } }
public EnumType Detekcija() { CustomPrincipal principal = Thread.CurrentPrincipal as CustomPrincipal; if (principal.IsInRole(Permissions.addentity.ToString()) && principal.IsInRole(Permissions.execute.ToString()) && principal.IsInRole(Permissions.modify.ToString())) { return(EnumType.Administrator); } if (principal.IsInRole(Permissions.execute.ToString()) && principal.IsInRole(Permissions.modify.ToString())) { return(EnumType.Operator); } else { return(EnumType.Customer); } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); SerializeCustomPrincipal serializeModel = serializer.Deserialize <SerializeCustomPrincipal>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(serializeModel.name, serializeModel.role, serializeModel.email, serializeModel.userId); HttpContext.Current.User = newUser; } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); GebruikerVM serializeModel = JsonConvert.DeserializeObject <GebruikerVM>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.UserId = serializeModel.Id; newUser.FirstName = serializeModel.Naam; newUser.LastName = serializeModel.Achternaam; HttpContext.Current.User = newUser; } }
public void SetCookieSecurityInformation() { var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { return; } var authTicket = FormsAuthentication.Decrypt(authCookie.Value); var userKey = Guid.Parse(authTicket.UserData); var userIdentity = new GenericIdentity(authTicket.Name); var userPrincipal = new CustomPrincipal(userIdentity, userKey); HttpContext.Current.User = userPrincipal; }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); UserModel serializeModel = JsonConvert.DeserializeObject <UserModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.Email = serializeModel.Email; newUser.Name = serializeModel.Name; newUser.Roles = serializeModel.Roles; HttpContext.Current.User = newUser; } }
public void SignOut(SignOutOption signOutOption) { var identity = (CustomIdentity)Thread.CurrentPrincipal?.Identity; // var cacheKeyProfile = CacheKeyOption.Profile + "-" + identity.UserId; var sessions = _repositorySession.Get().Where(e => e.Creator.Id == identity.UserId).ToList(); if (sessions.Count > 0) { foreach (var session in sessions) { _repositorySessionHistory.Add(new SessionHistory { Id = GuidHelper.NewGuid(), Creator = session.Creator, CreationTime = session.CreationTime, LastModificationTime = DateTime.Now, LogoutType = signOutOption.ToString(), }, true); _repositorySession.Delete(session, true); } } // Kimlik nesnesi boşaltılıp yeniden oluşturuluyor identity = new CustomIdentity(); identity.AddClaims(new[] { new Claim("UserId", Guid.Empty.ToString()), new Claim("Username", string.Empty), new Claim("Password", string.Empty), new Claim("FirstName", string.Empty), new Claim("LastName", string.Empty), new Claim("DisplayName", string.Empty), new Claim("Email", string.Empty), new Claim("LanguageId", Guid.Empty.ToString()), new Claim("IsAuthenticated", false.ToString()), }); var principal = new CustomPrincipal(identity); // Thread geçerli kimlik bilgisi ayarlanıyor Thread.CurrentPrincipal = principal; // _cacheService.Remove(cacheKeyProfile); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { CustomPrincipal cp = HttpContext.Current.User as CustomPrincipal; CSS requester = new CSS(); //get facilitator info Facilitator fac = new Facilitator(); if (HttpContext.Current.User.Identity.IsAuthenticated) { fac = requester.GetFacilitator(Convert.ToInt32(cp.Identity.Name)); //tbEventDate.Text = DateTime.Today.ToString(); } } }
public static CustomPrincipal CookieToIdentity(HttpCookie authCookie) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); CustomPrincipalSerializeModel serializeModel = serializer.Deserialize <CustomPrincipalSerializeModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.Id = serializeModel.Id; newUser.FirstName = serializeModel.FName; newUser.Roles = serializeModel.Roles; newUser.AvatarPath = serializeModel.AvatarPath; return(newUser); }
public ActionResult MyProject() { CustomPrincipal customPrincipal = (CustomPrincipal)User; if (customPrincipal == null || (customPrincipal.TeamId == 0)) { return(RedirectToAction("MyTeamRegister")); } ProjectModel userProject = TeamProjects(customPrincipal.TeamId); if (userProject.Proj_ID != 0) { return(View(userProject)); } return(RedirectToAction("MyProjectCreate")); }
public ActionResult MyTeam() { if (User.Identity.IsAuthenticated) { CustomPrincipal customPrincipal = (CustomPrincipal)User; if (customPrincipal == null || (customPrincipal.TeamId == 0)) { return(RedirectToAction("MyTeamRegister")); } TeamModel team = GetTeam(((CustomPrincipal)User).TeamId); var userList = TeamMembers(((CustomPrincipal)User).TeamId); team.Users = userList; MyTeamViewModel teamView = new MyTeamViewModel { Team_Name = team.Team_Name, Users = team.Users }; foreach (UserModel user in userList) { if (user.User_ID == team.Team_Leader) { teamView.Team_Leader = user.First_Name + " " + user.Last_Name; } } for (int i = 0; i < userList.Count; i++) { UserModel user = userList[i]; if (user.User_ID == team.Team_Leader) { teamView.Users.Remove(user); } } ViewBag.Team_Name = teamView.Team_Name; ViewBag.Team_Leader = teamView.Team_Leader; return(View(teamView.Users)); } return(RedirectToAction("MyTeamRegister")); }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { return; } FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); var userData = authTicket.UserData; CustomIdentitiy identity = new CustomIdentitiy(authTicket); CustomPrincipal principal = new CustomPrincipal(identity, userData); HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; }
private void Auth(UserDto user, Action resetAction) { try { //-------------------------------------------------------------------------- CustomPrincipal customPrincipal = Thread.CurrentPrincipal as CustomPrincipal; var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.Email, user.Email), }; foreach (var role in user.Roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } customPrincipal = new CustomPrincipal(new ClaimsIdentity(claims, "custom")); if (customPrincipal == null) { throw new ArgumentException("Неудача."); } Thread.CurrentPrincipal = customPrincipal; // customPrincipal.Identity = new CustomIdentity(user.Username, user.Email, user.Roles); //-------------------------------------------------------------------------- NotifyPropertyChanged("AuthenticatedUser"); NotifyPropertyChanged("IsAuthenticated"); _loginCommand.RaiseCanExecuteChanged(); _logoutCommand.RaiseCanExecuteChanged(); if (resetAction != null) { resetAction(); } Status = string.Empty; } catch (UnauthorizedAccessException) { Status = "Login failed! Измените учетные данные и повторите попытку."; } catch (Exception ex) { Status = string.Format("ERROR: {0}", ex.Message); } if (IsAuthenticated) { ShowView(); } }
private static void CheckToken(string token, out bool valid) { valid = false; try { var bpath = Convert.FromBase64String(token); token = System.Text.Encoding.Default.GetString(bpath); var jsonStr = "{'" + token.Replace("&", "','").Replace("=", "':'") + "'}"; var serializer = new JavaScriptSerializer(); var objs = serializer.Deserialize<TokenModel>(jsonStr); using (var accountService = DependencyResolver.Current.GetService<IAccountService>()) { var user = accountService.GetAccounts().FirstOrDefault(n => n.AppId == objs.appid && n.IsDeleted == false); if (user == null) return; var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); var timestamp = (int)(DateTime.Now - startTime).TotalSeconds; for (var i = 0; i < 600; i++) { var signature = SHA1_Hash(string.Format("appsecret={0}&random={1}×tamp={2}", user.AppSecret, objs.random, timestamp - i)); if (objs.signature.ToUpper() == signature) { valid = true; break; } } if (!valid) return; var identity = new CustomIdentity(user); var principal = new CustomPrincipal(identity); HttpContext.Current.User = principal; //得到token 如果超时则重新获取 if (user.GetAccessTokenDateTime == null || DateTime.Now.Subtract(user.GetAccessTokenDateTime.Value).Duration().TotalSeconds > 7000) { var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", user.AppId, user.AppSecret); var accessToken = JsonConvert.DeserializeObject<AccessToken>(HttpGet(url)).access_token; user.GetAccessTokenDateTime = DateTime.Now; user.AccessToken = accessToken; accountService.Update(); } } } catch (Exception) { valid = false; } }
/// <summary> /// Stores view mode in cookie when a user select a new view mode /// </summary> /// <param name="diseaseSelection"></param> private void OnDiseaseSelect(string diseaseSelection) { if (diseaseSelection != "") { string dz = diseaseSelection; HttpCookie diseaseView = new HttpCookie("diseaseView", dz); diseaseView.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(diseaseView); CustomPrincipal cp = System.Threading.Thread.CurrentPrincipal as CustomPrincipal; cp.UserProfile["diseaseView"] = dz; //Set Disease View Display currentDiseaseView.Text = dz.ToString(); } }
void Application_OnPostAuthenticateRequest(object sender, EventArgs e) { LIMSHelper.UrlHelper urlHelper = new LIMSHelper.UrlHelper(Context.Request.RequestContext); HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket.Expired == false) { CustomPrincipal principal = new CustomPrincipal(authTicket.Name, authTicket.UserData); principal.ClientIp = urlHelper.ClientIP; HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal; } } }
public ActionResult AddTask(TaskModel task) { if (!ModelState.IsValid) { return(View("AddTask")); } CustomPrincipal customPrincipal = (CustomPrincipal)User; UserModel user = GetUser(customPrincipal.Email); TeamModel team = GetTeam(user.Team_ID); task.Project_ID = team.Proj_ID; if (AddTask(task.Project_ID, task.Task_Desc, task.Time_Req, task.Task_Due)) { return(RedirectToAction("MyTasks")); } return(View("AddTask")); }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { var cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName); if (cookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); UserData userdata = JsonConvert.DeserializeObject <UserData>(ticket.UserData); CustomPrincipal customprincipal = new CustomPrincipal(ticket.Name); customprincipal.FirstName = userdata.FirstName; customprincipal.Username = userdata.Username; customprincipal.Roles = userdata.Roles; customprincipal.NotificationNo = userdata.NotificationNo; HttpContext.Current.User = customprincipal; } }
public override void OnAuthorization(AuthorizationContext filterContext) { if (string.IsNullOrEmpty(SessionPersister.EmailUsuario)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login", ReturnUrl = filterContext.HttpContext.Request.RawUrl })); } else { _SGCModel db = new _SGCModel(); string mail = db.usuarios.Where(u => u.email.Equals(SessionPersister.EmailUsuario)).FirstOrDefault().email; int id = db.usuarios.Where(u => u.email.Equals(SessionPersister.EmailUsuario)).FirstOrDefault().id; CustomPrincipal mp = new CustomPrincipal(id, mail); if (!mp.IsInRole(SGC_AccessCode)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Unauthorize" })); } } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.UserId = serializeModel.UserId; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; newUser.roles = serializeModel.roles; HttpContext.Current.User = newUser; } }
private static string ObtenerArchivo(HttpContext context, long archivoId) { CustomPrincipal principal = context.User as CustomPrincipal; CustomIdentity identity = principal.Identity as CustomIdentity; IComprobanteService svc = ServiceFactory.GetComprobanteService(); string file = string.Empty; if (principal.IsInRole(Roles.Administrador)) { file = svc.ObtenerArchivo(archivoId); } else if (principal.IsInRole(Roles.Cliente)) { file = svc.ObtenerArchivo(archivoId, identity.ClientId.Value); } return(file); }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies["UserCookie"]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); var serializeModel = JsonConvert.DeserializeObject <UserViewModel>(authTicket.UserData); CustomPrincipal principal = new CustomPrincipal(authTicket.Name); principal.Email = serializeModel.Email; principal.Roles = serializeModel.Role.ToString(); HttpContext.Current.User = principal; } }
public SampleCustomPrincipal(CustomPrincipal principal) : base((new SampleCustomIdentity(principal.Identity as CustomIdentity))) { //Map external principal to local principal MapPrincipal(principal); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); CustomPrincipal customPrincipal = new CustomPrincipal(); AppDomain.CurrentDomain.SetThreadPrincipal(customPrincipal); AuthenticationService authenticationService = new AuthenticationService(App._dataDC); if (e != null && e.Args != null && e.Args.Count<string>() > 0) { try { Dictionary<string, string> dic = this.MakeDictionary(e.Args); if (dic != null) { try { User user = authenticationService.AuthenticateUser(dic["User"], dic["Pass"]); customPrincipal = (Thread.CurrentPrincipal as CustomPrincipal); if (customPrincipal == null) { throw new ArgumentException("The application's default thread principal must be set to a CustomPrincipal object on startup."); } customPrincipal.Identity = new CustomIdentity(user.Username, user.Role); } catch (UnauthorizedAccessException exp) { MessageBox.Show("Login failed! Please provide some valid credentials."); } catch (Exception ex) { MessageBox.Show("ERROR: {0}", ex.Message); } if (this.IsAuthenticated) { MainWindowViewModel viewModel = null; MainWindow window = new MainWindow(); string notamType = null; try { if (dic.ContainsKey("GetAddr")) { var aftnService = new AftnService(App._dataDC2); var AftnList = aftnService.GetAftnList().OrderBy(t => t.Series).ToList(); string strFinal=""; foreach(var aftn in AftnList) { strFinal += aftn.Series + "=" + aftn.AftnList+"\n"; } System.IO.File.WriteAllText("C:\\NOTDIR\\ADDR.TXT", strFinal); Application.Current.Shutdown(); return; } if (dic["NotamType"] != null) { notamType = dic["NotamType"].Substring(dic["NotamType"].Length - 1); } if (dic["NotamType"].Contains("NOTAM")) { if (dic["Originat"].IndexOf("OI") != 0) { IntlNotam notam = new IntlNotam { Number = dic.ContainsKey("Num") ? dic["Num"] : "", NotamType = notamType, SendTime = dic.ContainsKey("Filling") ? dic["Filling"] : "", Type = dic.ContainsKey("Type") ? dic["Type"] : "", Year = dic.ContainsKey("year") ? dic["year"] : "", RefType = dic.ContainsKey("RefT") ? dic["RefT"] : "", RefYear = dic.ContainsKey("RefY") ? dic["RefY"] : "", RefNum = dic.ContainsKey("RefN") ? dic["RefN"] : "", LowerLimit = dic.ContainsKey("Lower") ? dic["Lower"] : "", HigherLimit = dic.ContainsKey("Upper") ? dic["Upper"] : "", Latitude = dic.ContainsKey("Latitude") ? dic["Latitude"] : "", Longtitude = dic.ContainsKey("Longtitude") ? dic["Longtitude"] : "", Radius = dic.ContainsKey("Radius") ? dic["Radius"] : "", FirAero = dic.ContainsKey("FirAd") ? dic["FirAd"] : "", FromDate = dic.ContainsKey("FromDate") ? dic["FromDate"] : "", ToDate = dic.ContainsKey("ToDate") ? dic["ToDate"] : "", PermEst = dic.ContainsKey("EstPerm") ? dic["EstPerm"] : "", EFreeText = dic.ContainsKey("ItemE") ? dic["ItemE"] : "", DFreeText = dic.ContainsKey("ItemD") ? dic["ItemD"] : "", FFreeText = dic.ContainsKey("ItemF") ? dic["ItemF"] : "", GFreeText = dic.ContainsKey("ItemG") ? dic["ItemG"] : "", Origin = dic.ContainsKey("FIR") ? ( from o in App._dataDC2.Origins where o.Code.Equals(dic["Originat"]) select o).FirstOrDefault<Origin>() : null, FIR = dic.ContainsKey("FIR") ? App._dataDC2.FIRs.Where(n => (n.Code.Length==4) && n.Code.Substring(0,2).Equals(dic["FIR"].Substring(0,2))).FirstOrDefault() : null, Status = "D", NotamCode = dic.ContainsKey("QCode") ? ( from o in App._dataDC2.NotamCodes where (o.Subject + o.Condition).Equals(dic["QCode"]) select o).FirstOrDefault<NotamCode>() : null }; IntlNotamService intlNotamService = new IntlNotamService(App._dataDC2); if (!intlNotamService.ContainsNotam(notam)) { intlNotamService.Insert(notam); // MessageBox.Show("International NOTAM Inserted To Database Successfully"); } else { // MessageBox.Show("International NOTAM Already Inserted To Database"); } Application.Current.Shutdown(); return; } // if (!dic.ContainsKey("FIR")) // { // dic.Add("FIR", "OIIX"); // } // Notam notam2 = new Notam // { // Number = "", // NotamType = notamType, // SendTime = dic.ContainsKey("Filling") ? dic["Filling"] : "", // Type = dic.ContainsKey("Type") ? dic["Type"] : "", // Year = dic.ContainsKey("year") ? dic["year"] : "", // RefType = dic.ContainsKey("RefT") ? dic["RefT"] : "", // RefYear = dic.ContainsKey("RefY") ? dic["RefY"] : "", // RefNum = dic.ContainsKey("RefN") ? dic["RefN"] : "", // LowerLimit = dic.ContainsKey("Lower") ? dic["Lower"] : "", // HigherLimit = dic.ContainsKey("Upper") ? dic["Upper"] : "", // Latitude = dic.ContainsKey("Latitude") ? dic["Latitude"] : "", // Longtitude = dic.ContainsKey("Longtitude") ? dic["Longtitude"] : "", // Radius = dic.ContainsKey("Radius") ? dic["Radius"] : "", // FirAero = dic.ContainsKey("FirAd") ? dic["FirAd"] : "", // FromDate = dic.ContainsKey("FromDate") ? dic["FromDate"] : "", // ToDate = dic.ContainsKey("ToDate") ? dic["ToDate"] : "", // PermEst = dic.ContainsKey("EstPerm") ? dic["EstPerm"] : "", // EFreeText = dic.ContainsKey("ItemE") ? dic["ItemE"] : "", // DFreeText = dic.ContainsKey("ItemD") ? dic["ItemD"] : "", // FFreeText = dic.ContainsKey("ItemF") ? dic["ItemF"] : "", // GFreeText = dic.ContainsKey("ItemG") ? dic["ItemG"] : "", // Origin = ( // from o in App._dataDC2.Origins // where o.Code.Equals(dic["Originat"]) // select o).FirstOrDefault<Origin>(), // FIR = ( // from o in App._dataDC2.FIRs // where o.Code.Equals(dic["FIR"]) // select o).FirstOrDefault<FIR>(), // Status = "D", // NotamCode = dic.ContainsKey("QCode") ? ( // from o in App._dataDC2.NotamCodes // where (o.Subject + o.Condition).Equals(dic["QCode"]) // select o).FirstOrDefault<NotamCode>() : null // }; // viewModel = new MainWindowViewModel(App._dataDC2, notam2); } else { if (dic["NotamType"].Contains("RQN")) { SendRQN(dic, App._dataDC2); } else { SendRQL(dic); } Application.Current.Shutdown(); return; } } catch (System.Exception ex) { MessageBox.Show(ex.Message); Application.Current.Shutdown(); return; } EventHandler handler = null; handler = delegate { viewModel.RequestClose -= handler; window.Close(); }; viewModel.RequestClose += handler; window.DataContext = viewModel; window.ShowDialog(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } if (!IsAuthenticated) { //Show the login view AuthenticationViewModel viewModel = new AuthenticationViewModel(authenticationService);
public static bool IsInRole(this Controller controller, Role role) { CustomPrincipal prinzipal = new CustomPrincipal(controller.HttpContext.User.Identity); return prinzipal.IsInRole(role); }
// Reference: http://nerddinnerbook.s3.amazonaws.com/Part12.htm // Yes .. Nerd Dinner to the rescue! and we come full circle... private static HomeController HomeController(IDocumentSession documentSession, int userId = 0, string displayName = null, string[] roles = null) { Condition.Requires(documentSession); // Some fake Authentication stuff. var customIdentity = new CustomIdentity(userId, displayName); var customPrincipal = new CustomPrincipal(customIdentity, roles); var mockControllerContext = new Mock<ControllerContext>(); mockControllerContext.Setup(x => x.HttpContext.User).Returns(customPrincipal); var homeController = new HomeController(documentSession) {ControllerContext = mockControllerContext.Object}; return homeController; }
/// <summary> /// Map external principal to local /// </summary> /// <param name="principal"></param> private void MapPrincipal(CustomPrincipal principal) { //TODO: Add your principal mapping logic here //The principal mapping solve the user permission data exchange problem between external and local system }
private static void CheckToken(string token, out bool valid) { valid = false; try { var bpath = Convert.FromBase64String(token); token = System.Text.Encoding.Default.GetString(bpath); var jsonStr = "{'" + token.Replace("&", "','").Replace("=", "':'") + "'}"; var serializer = new JavaScriptSerializer(); var objs = serializer.Deserialize<TokenModel>(jsonStr); using (var accountService = DependencyResolver.Current.GetService<IAccountService>()) { var user = accountService.GetAccounts().FirstOrDefault(n => n.Id == objs.appid && n.IsDeleted == false); if (user == null) return; var signature = SHA1_Hash(string.Format("appsecret={0}&random={1}", user.Token, objs.random)); if (objs.signature.ToUpper() != signature) return; valid = true; var identity = new CustomIdentity(user); var principal = new CustomPrincipal(identity); HttpContext.Current.User = principal; } } catch (Exception) { valid = false; } }
public async Task ConnectionCanStartWithAuthenicatedUserAndQueryString() { using (var host = new MemoryHost()) { host.Configure(app => { Func<AppFunc, AppFunc> middleware = (next) => { return env => { if (((string)env["owin.RequestQueryString"]).IndexOf("access_token") == -1) { return next(env); } var user = new CustomPrincipal { Name = "Bob", IsAuthenticated = true, Roles = new[] { "User" } }; env["server.User"] = user; return next(env); }; }; app.Use(middleware); var config = new ConnectionConfiguration { Resolver = new DefaultDependencyResolver() }; app.MapSignalR<MyAuthenticatedConnection>("/authenticatedConnection", config); }); var connection = new Connection("http://foo/authenticatedConnection", "access_token=1234"); using (connection) { await connection.Start(host); Assert.Equal(connection.State, ConnectionState.Connected); } } }