protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now string acc_name = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string roles = string.Empty; using (projectShopEntities entities = new projectShopEntities()) { Account account = entities.Accounts.SingleOrDefault(u => u.acc_name == acc_name); roles = account.Roles; } //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(acc_name, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now string email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string roles = string.Empty; InvestNetworkEntities dataContext = new InvestNetworkEntities(); User user = dataContext.Users.SingleOrDefault(u => u.Email == email); //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(email, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; var accountBusiness = DependencyResolver.Current.GetService<IAccountBusiness>(); string roles = accountBusiness.VerificarTipoUsuario(username); //using (userDbEntities entities = new userDbEntities()) //{ // User user = entities.Users.SingleOrDefault(u => u.username == username); // roles = user.Roles; //} //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } }
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { if (FormsAuthentication.CookiesSupported) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( Request.Cookies[FormsAuthentication.FormsCookieName].Value); args.User = new System.Security.Principal.GenericPrincipal( new FormsIdentity(ticket), new string[0]); } catch (Exception e) { // Decrypt method failed. } } } else { throw new HttpException("Cookieless Forms Authentication is not " + "supported for this application."); } }
// FROM http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now string customerUsername = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string roles = string.Empty; using (DBModelContainer db = new DBModelContainer()) { Customer customer = db.Customers.SingleOrDefault(u => u.customerUsername == customerUsername); roles = customer.CustomerRole.roleName; Console.Write(roles); } //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(customerUsername, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { var context = System.Web.HttpContext.Current; var request = System.Web.HttpContext.Current.Request; HttpCookie authCookie = request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); var roles = authTicket.UserData.Split('|'); var user = new GenericPrincipal(new GenericIdentity(authTicket.Name, "Forms"), roles); e.User = context.User = Thread.CurrentPrincipal = user; UserSession.UpdateCurrentUser("", authTicket.Name); } } catch (Exception) { //somehting went wrong } } } }
protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { //if (Request.Cookies[FormsAuthentication.FormsCookieName].Value != null) //{ //} }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; if (string.IsNullOrEmpty(username)) { //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), new string[] { "User" }); } } catch (Exception) { //somehting went wrong } } } }
/// <summary>Global event: called during authentication, see the remarks in <see cref="T:System.Web.Security.FormsAuthenticationEventHandler" /></summary> /// <remarks> /// Fixes .net 4.5 authentication issue when the mode is set to "Forms" instead of Sitecore's default of None, by assigning Sitecore's context user to args.User</remarks> public virtual void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { string frameworkVersion = this.GetFrameworkVersion(); if (!string.IsNullOrEmpty(frameworkVersion) && frameworkVersion.StartsWith("v4.", System.StringComparison.InvariantCultureIgnoreCase)) { args.User = Sitecore.Context.User; } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported) { var isPrimary = !e.Context.Request.Path.Contains("lll/"); e.User = new AppAuthenticationService().GetAuthenticatedUser(isPrimary); } }
public void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { HttpCookie cookie = e.Context.Request.Cookies[ FormsAuthentication.FormsCookieName ]; if (cookie == null) return; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); PestControlModel model = (PestControlModel) container[ typeof(PestControlModel) ]; e.User = model.Users.FindByEmail( ticket.Name ); }
//OR: Application_PostAuthenticateRequest protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //Discover user's name string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string roles = string.Empty; //using (userDbEntities entities = new userDbEntities()) //{ // User user = entities.Users.SingleOrDefault(u => u.username == username); // roles = user.Roles; //} ////let us extract the roles from our own custom cookie var context = new EAFormDBContext(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); //Query UserManager to discover role(s) for this user to store in IPrincipal ApplicationUser appUser = UserManager.FindByName(username); if (appUser == null) { //They've logged in BUT are not in any of our lists Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Logged in user does not have a role. User name = " + username)); } else { var delim = ""; foreach (var role in appUser.Roles) { roles += delim + role.Role.Name; delim = ";"; } } //Set the Pricipal with roles e.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } } } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported != true) return; if (Request.Cookies[FormsAuthentication.FormsCookieName] == null || string.IsNullOrEmpty(Request.Cookies[FormsAuthentication.FormsCookieName].Value)) return; var formsAuthenticationTicket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value); if (formsAuthenticationTicket == null) return; var username = formsAuthenticationTicket.Name; var userService = UnityConfig.GetConfiguredContainer().Resolve<IUserService>(); var user = userService.GetByUsername(username); e.User = new GenericPrincipal(new GenericIdentity(username, "Forms"), new[] { user.UserType.ToString() }); }
void OnAuthenticateRequest (object sender, EventArgs args) { HttpApplication app = (HttpApplication) sender; HttpContext context = app.Context; AuthConfig config = (AuthConfig) context.GetConfig ("system.web/authentication"); if (config == null || config.Mode != AuthenticationMode.Forms) { return; } string cookieName = config.CookieName; string cookiePath = config.CookiePath; string loginPage = config.LoginUrl; string reqPath = context.Request.PhysicalPath; string loginPath = context.Request.MapPath (loginPage); context.SkipAuthorization = (reqPath == loginPath); FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context); if (Authenticate != null) Authenticate (this, formArgs); bool contextUserNull = (context.User == null); if (formArgs.User != null || !contextUserNull) { if (contextUserNull) context.User = formArgs.User; return; } HttpCookie cookie = context.Request.Cookies [cookieName]; if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now)) return; FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt (cookie.Value); if (ticket == null || (ticket.IsPersistent && ticket.Expired)) return; if (config.SlidingExpiration) ticket = FormsAuthentication.RenewTicketIfOld (ticket); context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]); cookie.Value = FormsAuthentication.Encrypt (ticket); cookie.Path = cookiePath; if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; context.Response.Cookies.Add (cookie); }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (!FormsAuthentication.CookiesSupported) return; if (Request.Cookies[FormsAuthentication.FormsCookieName] == null) return; try { var email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(email, "Forms"), null); } catch { } }
protected void FormsAuthentication_OnAuthentication(object sender, FormsAuthenticationEventArgs args) { _logger.Info("Authentication user..."); //HACK: How do I inject the security provider into the global asax? //Perhaps this : http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx var securityProvider = Startup.Container.Resolve<ISecurityProvider>(); var principal = securityProvider.GetPrincipal(args.Context.Request); if (principal != null) { args.Context.User = principal; _logger.Info("User authenticated."); } else { _logger.Info("User is anonymous."); } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; /// we can add role related code here /// HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(username, "Forms"), null); } catch (Exception ex) { } } } }
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { if (!FormsAuthentication.CookiesSupported) { throw new HttpException("Cookieless Forms Authentication is not supported for this application."); } HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authenticationCookie != null) { FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value); if (!string.IsNullOrEmpty(authenticationTicket.UserData) && !authenticationTicket.Expired) { DateTime ticketFirstCreated; if (DateTime.TryParse(authenticationTicket.UserData, out ticketFirstCreated)) { if (ticketFirstCreated.AddMinutes(int.Parse(System.Configuration.ConfigurationManager.AppSettings["UserActiveTimeout"])) <= DateTime.Now) { FormsAuthentication.SignOut(); FormsAuthentication.RedirectToLoginPage(); } else { long ticketHalfLife = authenticationTicket.Expiration.Subtract(authenticationTicket.IssueDate).Ticks / 2; if (authenticationTicket.IssueDate.AddTicks(ticketHalfLife) <= DateTime.Now) { FormsAuthenticationTicket newAuthenticationTicket = new FormsAuthenticationTicket( 1, authenticationTicket.Name, DateTime.Now, DateTime.Now.AddMinutes(int.Parse(System.Configuration.ConfigurationManager.AppSettings["UserInactiveTimeout"])), false, authenticationTicket.UserData, FormsAuthentication.FormsCookiePath); HttpCookie newAuthenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(newAuthenticationTicket)); Request.Cookies.Remove(authenticationCookie.Name); Response.Cookies.Add(newAuthenticationCookie); } } } } } }
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now var httpCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (httpCookie != null) { string username = FormsAuthentication.Decrypt(httpCookie.Value).Name; string roles = string.Empty; using (var data = new db_ultramedicaDataContext(Helper.ConnectionString())) { var user = data.USERs.SingleOrDefault(u => u.USERNAME == username); if (user != null) roles = user.ROLES; } //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(',')); } } catch (Exception) { //somehting went wrong } } } }
public static void FormsAuthentication_OnAuthenticate( object sender, FormsAuthenticationEventArgs args) { if (FormsAuthentication.CookiesSupported) { HttpRequest request = HttpContext.Current.Request; if (request.Cookies[FormsAuthentication.FormsCookieName] != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( request.Cookies[FormsAuthentication.FormsCookieName].Value); string[] parts = ticket.UserData.Split(';'); int userId = int.Parse(parts[0]); string acctgId = parts[1]; byte bRole = byte.Parse(parts[2]); string internalFranchName = parts[3]; if (!Enum.IsDefined(typeof(SecurityRole), bRole)) throw new Exception("Incorrect Users.UserRole value"); // if (HttpContext.Current.Request.Cookies["InternalFranchName"] == null || HttpContext.Current.Request.Cookies["InternalFranchName"].Value != internalFranchName) { //SiteContext._internalFranchName = internalFranchName; HttpCookie coockie = new HttpCookie("InternalFranchName"); coockie.Domain = "rmsauto.ru"; coockie.Path = "/"; coockie.Value = HttpUtility.HtmlEncode(internalFranchName); HttpContext.Current.Request.Cookies.Add(coockie); HttpContext.Current.Response.Cookies.Add(coockie); HttpCookie CityNamecoockie = new HttpCookie("cityName"); CityNamecoockie.Domain = "rmsauto.ru"; CityNamecoockie.Path = "/"; IEnumerable<City> cities; using (var dcCommon = new RmsAuto.Store.Entities.dcCommonDataContext()) { //Извлекаем наборы данных в списки, так как LINQ to SQL не дает выполнять запросы к различным контекстам //TODO: сделать AcctgRefCatalog.Cities, вынести в справочник, чтобы не лезть в базу каждый раз cities = dcCommon.Cities.Select(x => x).ToList(); } //var regionId = AcctgRefCatalog.RmsFranches[(string)context.Request.QueryString[UrlKeys.Activation.FranchCode]].RegionID; var regionId = AcctgRefCatalog.RmsFranches[internalFranchName].RegionID; CityNamecoockie.Value = HttpUtility.UrlEncodeUnicode(cities.Where(x => x.CityID == regionId).Select(x => x.Name).FirstOrDefault()); HttpContext.Current.Request.Cookies.Add(CityNamecoockie); HttpContext.Current.Response.Cookies.Add(CityNamecoockie); } SecurityRole role = (SecurityRole)bRole; var user = new CustomPrincipal( new FormsIdentity(ticket), new string[] { role.ToString() }, userId, acctgId, role, internalFranchName); args.User = user; } } else { //DO NOTHING //throw new HttpException( "Cookieless Forms Authentication is not " + // "supported for this application." ); } }
protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { RmsAuto.Store.Web.LogonService.FormsAuthentication_OnAuthenticate(sender, args); }
void OnAuthenticateRequest (object sender, EventArgs args) { HttpApplication app = (HttpApplication) sender; HttpContext context = app.Context; string cookieName; string cookiePath; string loginPage; bool slidingExpiration; InitConfig (context); if (_config == null || _config.Mode != AuthenticationMode.Forms) { return; } cookieName = _config.Forms.Name; cookiePath = _config.Forms.Path; loginPage = _config.Forms.LoginUrl; slidingExpiration = _config.Forms.SlidingExpiration; if (!VirtualPathUtility.IsRooted (loginPage)) loginPage = "~/" + loginPage; string reqPath = String.Empty; string loginPath = null; try { reqPath = context.Request.PhysicalPath; loginPath = context.Request.MapPath (loginPage); } catch {} // ignore context.SkipAuthorization = String.Compare (reqPath, loginPath, RuntimeHelpers.CaseInsensitive, Helpers.InvariantCulture) == 0; //TODO: need to check that the handler is System.Web.Handlers.AssemblyResourceLoader type string filePath = context.Request.FilePath; if (filePath.Length > 15 && String.CompareOrdinal ("WebResource.axd", 0, filePath, filePath.Length - 15, 15) == 0) context.SkipAuthorization = true; FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context); FormsAuthenticationEventHandler eh = events [authenticateEvent] as FormsAuthenticationEventHandler; if (eh != null) eh (this, formArgs); bool contextUserNull = (context.User == null); if (formArgs.User != null || !contextUserNull) { if (contextUserNull) context.User = formArgs.User; return; } HttpCookie cookie = context.Request.Cookies [cookieName]; if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now)) return; FormsAuthenticationTicket ticket = null; try { ticket = FormsAuthentication.Decrypt (cookie.Value); } catch (ArgumentException) { // incorrect cookie value, suppress the exception return; } if (ticket == null || (!ticket.IsPersistent && ticket.Expired)) return; FormsAuthenticationTicket oldticket = ticket; if (slidingExpiration) ticket = FormsAuthentication.RenewTicketIfOld (ticket); context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]); if (cookie.Expires == DateTime.MinValue && oldticket == ticket) return; cookie.Value = FormsAuthentication.Encrypt (ticket); cookie.Path = cookiePath; if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; context.Response.Cookies.Add (cookie); }
public static string FormsAuthEventArgsToString(FormsAuthenticationEventArgs faa) { string principalDisplay = "UNDEFINED"; if (faa != null && faa.User != null) { principalDisplay = IPrincipalToString(faa.User); } return string.Format("User[{0}]", principalDisplay); }
//////////////////////////////////////////////////////////// // OnAuthenticate: Forms Authentication modules can override // this method to create a Forms IPrincipal object from // a WindowsIdentity private void OnAuthenticate(FormsAuthenticationEventArgs e) { HttpCookie cookie = null; //////////////////////////////////////////////////////////// // Step 1: If there are event handlers, invoke the handlers if (_eventHandler != null) { _eventHandler(this, e); } //////////////////////////////////////////////////////////// // Step 2: Check if the event handler create a user-object if (e.Context.User != null || e.User != null) { // It did e.Context.User = (e.Context.User == null ? e.User : e.Context.User); return; } //////////////////////////////////////////////////////////// // Step 3: Extract the cookie and create a ticket from it FormsAuthenticationTicket ticket = null; try { ticket = ExtractTicketFromCookie(e.Context, _FormsName); } catch (Exception) { ticket = null; } //////////////////////////////////////////////////////////// // Step 4: See if the ticket was created: No => exit immediately if (ticket == null || ticket.Expired) { return; } //////////////////////////////////////////////////////////// // Step 5: Renew the ticket FormsAuthenticationTicket ticket2 = ticket; if (FormsAuthentication.SlidingExpiration) { ticket2 = FormsAuthentication.RenewTicketIfOld(ticket); } //////////////////////////////////////////////////////////// // Step 6: Create a user object for the ticket e.Context.User = new GenericPrincipal(new FormsIdentity(ticket2), new String[0]); //////////////////////////////////////////////////////////// // Step 7: Browser does not send us the correct cookie-path // Update the cookie to show the correct path if (!ticket2.CookiePath.Equals("/")) { cookie = e.Context.Request.Cookies[_FormsName]; if (cookie != null) { cookie.Path = ticket2.CookiePath; if (ticket2.IsPersistent) { cookie.Expires = ticket2.Expiration; } } } //////////////////////////////////////////////////////////// // Step 8: If the ticket was renewed, save the ticket in the cookie if (ticket2 != ticket) { String strEnc = FormsAuthentication.Encrypt(ticket2); if (cookie != null) { cookie = e.Context.Request.Cookies[_FormsName]; } if (cookie == null) { cookie = new HttpCookie(_FormsName, strEnc); cookie.Path = ticket2.CookiePath; } if (ticket2.IsPersistent) { cookie.Expires = ticket2.Expiration; } cookie.Value = strEnc; cookie.Secure = FormsAuthentication.RequireSSL; } if (cookie != null) { e.Context.Response.Cookies.Add(cookie); } }
//////////////////////////////////////////////////////////// // OnAuthenticate: Forms Authentication modules can override // this method to create a Forms IPrincipal object from // a WindowsIdentity private void OnAuthenticate(FormsAuthenticationEventArgs e) { HttpCookie cookie = null; //////////////////////////////////////////////////////////// // Step 1: If there are event handlers, invoke the handlers if (_eventHandler != null) { _eventHandler(this, e); } //////////////////////////////////////////////////////////// // Step 2: Check if the event handler created a user-object if (e.Context.User != null) { // do nothing because someone else authenticated return; } if (e.User != null) { // the event handler created a user e.Context.SetPrincipalNoDemand(e.User); return; } //////////////////////////////////////////////////////////// // Step 3: Extract the cookie and create a ticket from it bool cookielessTicket = false; FormsAuthenticationTicket ticket = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket); //////////////////////////////////////////////////////////// // Step 4: See if the ticket was created: No => exit immediately if (ticket == null || ticket.Expired) { return; } //////////////////////////////////////////////////////////// // Step 5: Renew the ticket FormsAuthenticationTicket ticket2 = ticket; if (FormsAuthentication.SlidingExpiration) { ticket2 = FormsAuthentication.RenewTicketIfOld(ticket); } //////////////////////////////////////////////////////////// // Step 6: Create a user object for the ticket e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket2), new String[0])); //////////////////////////////////////////////////////////// // Step 7: Browser does not send us the correct cookie-path // Update the cookie to show the correct path if (!cookielessTicket && !ticket2.CookiePath.Equals("/")) { cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { cookie.Path = ticket2.CookiePath; } } //////////////////////////////////////////////////////////// // Step 8: If the ticket was renewed, save the ticket in the cookie if (ticket2 != ticket) { if (cookielessTicket && ticket2.CookiePath != "/" && ticket2.CookiePath.Length > 1) { FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket2.Version, ticket2.Name, ticket2.IssueDateUtc, ticket2.ExpirationUtc, ticket2.IsPersistent, ticket2.UserData, "/"); ticket2 = tempTicket; } String strEnc = FormsAuthentication.Encrypt(ticket2, !cookielessTicket); if (cookielessTicket) { e.Context.CookielessHelper.SetCookieValue('F', strEnc); e.Context.Response.Redirect(e.Context.Request.RawUrl); } else { if (cookie != null) { cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; } if (cookie == null) { cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEnc); cookie.Path = ticket2.CookiePath; } if (ticket2.IsPersistent) { cookie.Expires = ticket2.Expiration; } cookie.Value = strEnc; cookie.Secure = FormsAuthentication.RequireSSL; cookie.HttpOnly = true; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } e.Context.Response.Cookies.Remove(cookie.Name); e.Context.Response.Cookies.Add(cookie); } } }
void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e) { Log4NetHelper.Logger.Debug("Application_PostAuthenticateRequest called."); // Does the request require authentication if (RequestDoesNotRequireAuthentication()) return; HttpContext httpContext = HttpContext.Current; string cookieName = FormsAuthentication.FormsCookieName; Log4NetHelper.Logger.Debug("CookieName=" + (cookieName ?? "")); HttpCookie authCookie = httpContext.Request.Cookies[cookieName]; if (authCookie == null) { Log4NetHelper.Logger.Debug("AuthCookie was null"); return; } Log4NetHelper.Logger.Debug("CookieValue=" + authCookie.Value); FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); Log4NetHelper.Logger.Debug("Got authTicket"); int companyId; if (!Int32.TryParse(authTicket.UserData, out companyId)) { throw new CompanyIdNotFoundOnAuthenticationCookieException(authTicket.Name); } var userId = Guid.Parse(authTicket.Name); Log4NetHelper.Logger.Debug("Got userId=" + userId); try { Log4NetHelper.Logger.Debug("Loading user."); var customPrincipalFactory = ObjectFactory.GetInstance<ICustomPrincipalFactory>(); var customPrincipal = customPrincipalFactory.Create(companyId, userId); // Are we impersonating the user?? if (httpContext.Request.Cookies["Impersonate"] != null) { customPrincipal.MarkAsImpersonatingUser(); } Context.User = customPrincipal; Thread.CurrentPrincipal = customPrincipal; Log4NetHelper.Logger.Debug("User loaded."); // Sliding expiration on the authentication ticker if (FormsAuthentication.SlidingExpiration) { var newTicket = FormsAuthentication.RenewTicketIfOld(authTicket); if (newTicket != null && newTicket != authTicket) { Context.Response.Cookies.Remove(authTicket.Name); string encryptedTicket = FormsAuthentication.Encrypt(newTicket); var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath, Expires = newTicket.Expiration }; HttpContext.Current.Response.Cookies.Add(httpCookie); } } } catch (BusinessSafeUnauthorisedException ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); Log.Add(2, string.Format("Business Safe Unauthorised Exception Encountered: {0}", ex.Message), ex); new BusinessSafeLogOut().LogOut(userId); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); Log.Add(2, string.Format("Post Authentication Exception Encountered: {0}", ex.Message), ex); throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized", new UserAuthenticationFilterException( string.Format("User could not be loaded successfully. User id was {0}", userId))); } }
private void Authenticate (object sender, FormsAuthenticationEventArgs e) { }
//////////////////////////////////////////////////////////// // OnAuthenticate: Forms Authentication modules can override // this method to create a Forms IPrincipal object from // a WindowsIdentity private void OnAuthenticate(FormsAuthenticationEventArgs e) { HttpCookie cookie = null; //////////////////////////////////////////////////////////// // Step 1: If there are event handlers, invoke the handlers if (_eventHandler != null) _eventHandler(this, e); //////////////////////////////////////////////////////////// // Step 2: Check if the event handler created a user-object if (e.Context.User != null) { // do nothing because someone else authenticated return; } if (e.User != null) { // the event handler created a user e.Context.SetPrincipalNoDemand(e.User); return; } //////////////////////////////////////////////////////////// // Step 3: Extract the cookie and create a ticket from it bool cookielessTicket = false; FormsAuthenticationTicket ticket = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket); //////////////////////////////////////////////////////////// // Step 4: See if the ticket was created: No => exit immediately if (ticket == null || ticket.Expired) return; //////////////////////////////////////////////////////////// // Step 5: Renew the ticket FormsAuthenticationTicket ticket2 = ticket; if (FormsAuthentication.SlidingExpiration) ticket2 = FormsAuthentication.RenewTicketIfOld(ticket); //////////////////////////////////////////////////////////// // Step 6: Create a user object for the ticket e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket2), new String[0])); //////////////////////////////////////////////////////////// // Step 7: Browser does not send us the correct cookie-path // Update the cookie to show the correct path if (!cookielessTicket && !ticket2.CookiePath.Equals("/")) { cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { cookie.Path = ticket2.CookiePath; } } //////////////////////////////////////////////////////////// // Step 8: If the ticket was renewed, save the ticket in the cookie if (ticket2 != ticket) { if(cookielessTicket && ticket2.CookiePath != "/" && ticket2.CookiePath.Length > 1) { FormsAuthenticationTicket tempTicket = FormsAuthenticationTicket.FromUtc(ticket2.Version, ticket2.Name, ticket2.IssueDateUtc, ticket2.ExpirationUtc, ticket2.IsPersistent, ticket2.UserData, "/"); ticket2 = tempTicket; } String strEnc = FormsAuthentication.Encrypt(ticket2, !cookielessTicket); if (cookielessTicket) { e.Context.CookielessHelper.SetCookieValue('F', strEnc); e.Context.Response.Redirect(e.Context.Request.RawUrl); } else { if (cookie != null) cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEnc); cookie.Path = ticket2.CookiePath; } if (ticket2.IsPersistent) cookie.Expires = ticket2.Expiration; cookie.Value = strEnc; cookie.Secure = FormsAuthentication.RequireSSL; cookie.HttpOnly = true; if (FormsAuthentication.CookieDomain != null) cookie.Domain = FormsAuthentication.CookieDomain; e.Context.Response.Cookies.Remove(cookie.Name); e.Context.Response.Cookies.Add(cookie); } } }
private void OnAuthenticate(FormsAuthenticationEventArgs e) { HttpCookie cookie = null; if (this._eventHandler != null) { this._eventHandler(this, e); } if (e.Context.User == null) { if (e.User != null) { e.Context.SetPrincipalNoDemand(e.User); } else { bool cookielessTicket = false; FormsAuthenticationTicket tOld = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket); if ((tOld != null) && !tOld.Expired) { FormsAuthenticationTicket ticket = tOld; if (FormsAuthentication.SlidingExpiration) { ticket = FormsAuthentication.RenewTicketIfOld(tOld); } e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket), new string[0])); if (!cookielessTicket && !ticket.CookiePath.Equals("/")) { cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { cookie.Path = ticket.CookiePath; } } if (ticket != tOld) { if ((cookielessTicket && (ticket.CookiePath != "/")) && (ticket.CookiePath.Length > 1)) { ticket = FormsAuthenticationTicket.FromUtc(ticket.Version, ticket.Name, ticket.IssueDateUtc, ticket.ExpirationUtc, ticket.IsPersistent, ticket.UserData, "/"); } string cookieValue = FormsAuthentication.Encrypt(ticket); if (cookielessTicket) { e.Context.CookielessHelper.SetCookieValue('F', cookieValue); e.Context.Response.Redirect(e.Context.Request.RawUrl); } else { if (cookie != null) { cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; } if (cookie == null) { cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue) { Path = ticket.CookiePath }; } if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } cookie.Value = cookieValue; cookie.Secure = FormsAuthentication.RequireSSL; cookie.HttpOnly = true; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } e.Context.Response.Cookies.Remove(cookie.Name); e.Context.Response.Cookies.Add(cookie); } } } } } }
void OnAuthenticateRequest(object sender, EventArgs args) { HttpApplication app = (HttpApplication)sender; HttpContext context = app.Context; string cookieName; string cookiePath; string loginPage; bool slidingExpiration; InitConfig(context); if (_config == null || _config.Mode != AuthenticationMode.Forms) { return; } #if NET_2_0 cookieName = _config.Forms.Name; cookiePath = _config.Forms.Path; loginPage = _config.Forms.LoginUrl; slidingExpiration = _config.Forms.SlidingExpiration; #else cookieName = _config.CookieName; cookiePath = _config.CookiePath; loginPage = _config.LoginUrl; slidingExpiration = _config.SlidingExpiration; #endif if (!VirtualPathUtility.IsRooted(loginPage)) { loginPage = "~/" + loginPage; } string reqPath = String.Empty; string loginPath = null; try { reqPath = context.Request.PhysicalPath; loginPath = context.Request.MapPath(loginPage); } catch {} // ignore context.SkipAuthorization = String.Compare(reqPath, loginPath, RuntimeHelpers.CaseInsensitive, Helpers.InvariantCulture) == 0; #if NET_2_0 //TODO: need to check that the handler is System.Web.Handlers.AssemblyResourceLoader type string filePath = context.Request.FilePath; if (filePath.Length > 15 && String.CompareOrdinal("WebResource.axd", 0, filePath, filePath.Length - 15, 15) == 0) { context.SkipAuthorization = true; } #endif FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs(context); FormsAuthenticationEventHandler eh = events [authenticateEvent] as FormsAuthenticationEventHandler; if (eh != null) { eh(this, formArgs); } bool contextUserNull = (context.User == null); if (formArgs.User != null || !contextUserNull) { if (contextUserNull) { context.User = formArgs.User; } return; } HttpCookie cookie = context.Request.Cookies [cookieName]; if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now)) { return; } FormsAuthenticationTicket ticket = null; try { ticket = FormsAuthentication.Decrypt(cookie.Value); } catch (ArgumentException) { // incorrect cookie value, suppress the exception return; } if (ticket == null || (!ticket.IsPersistent && ticket.Expired)) { return; } FormsAuthenticationTicket oldticket = ticket; if (slidingExpiration) { ticket = FormsAuthentication.RenewTicketIfOld(ticket); } context.User = new GenericPrincipal(new FormsIdentity(ticket), new string [0]); if (cookie.Expires == DateTime.MinValue && oldticket == ticket) { return; } cookie.Value = FormsAuthentication.Encrypt(ticket); cookie.Path = cookiePath; if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } context.Response.Cookies.Add(cookie); }
protected internal virtual void OnFormsAuthenticationModuleAuthenticate(object sender, FormsAuthenticationEventArgs e) { if(this.Authenticate != null) this.Authenticate(sender, e); }
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { }
public void FixtureSetUp () { context = new HttpContext (null); faea = new FormsAuthenticationEventArgs (context); }