private static void SlidingExpiration(HttpContext context, FormsAuthenticationTicket ticket, string cookieName) { FormsAuthenticationTicket ticket2 = null; if (FormsAuthentication.SlidingExpiration) { ticket2 = FormsAuthentication.RenewTicketIfOld(ticket); } else { ticket2 = ticket; } string str = FormsAuthentication.Encrypt(ticket2); HttpCookie cookie = context.Request.Cookies[cookieName]; if (cookie == null) { cookie = new HttpCookie(cookieName, str); cookie.Path = ticket2.CookiePath; } if (ticket.IsPersistent) { cookie.Expires = ticket2.Expiration; } cookie.Value = str; cookie.Secure = FormsAuthentication.RequireSSL; cookie.HttpOnly = true; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } context.Response.Cookies.Remove(cookie.Name); context.Response.Cookies.Add(cookie); }
/// <summary> /// Renews the forms authentication ticket & cookie /// </summary> /// <param name="http"></param> /// <param name="cookieName"></param> /// <param name="cookieDomain"></param> /// <param name="minutesPersisted"></param> /// <returns></returns> public static bool RenewAuthTicket(this HttpContextBase http, string cookieName, string cookieDomain, int minutesPersisted) { //get the ticket var ticket = GetAuthTicket(http, cookieName); //renew the ticket var renewed = FormsAuthentication.RenewTicketIfOld(ticket); if (renewed == null) { return(false); } //encrypt it var hash = FormsAuthentication.Encrypt(renewed); //write it to the response var cookie = new HttpCookie(cookieName, hash) { Expires = DateTime.Now.AddMinutes(minutesPersisted), Domain = cookieDomain }; //rewrite the cooke http.Response.Cookies.Remove(cookieName); http.Response.Cookies.Add(cookie); return(true); }
/// <summary> /// Sets a non-persistent cookie (i.e. not saved accross /// browser sessions) for the Forms Authentication state. /// </summary> /// <param name="userName">The username authenticated.</param> /// <param name="userTimezoneOffset">The user time zone offset</param> /// <param name="response">Response object</param> public static void SetSessionCookie(string userName, string userTimezoneOffset, HttpResponseBase response) { //FormsAuthentication.SetAuthCookie(userName, false); var strb = new StringBuilder(); strb.AppendFormat("userName={0}", userName); strb.AppendFormat(";userTimezoneOffset={0}", userTimezoneOffset); var dateToUse = ApplicationConfiguration.SystemBuildDateInMillis; if (ApplicationConfiguration.IsLocal()) { //if local we can safely use the starttime dateToUse = ApplicationConfiguration.StartTimeMillis; } strb.AppendFormat(";cookiesystemdate={0}", dateToUse); var cookie = FormsAuthentication.GetAuthCookie(userName, false); var ticket = FormsAuthentication.Decrypt(cookie.Value); var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, strb.ToString(), ticket.CookiePath); FormsAuthentication.RenewTicketIfOld(newTicket); var encTicket = FormsAuthentication.Encrypt(newTicket); cookie.Value = encTicket; response.Cookies.Add(cookie); }
public IPrincipal GetCurrent() { IPrincipal user = _context.User; // if they are already signed in, and conversion has happened if (user != null && user is MyCMSPrincipal) { return(user); } // if they are signed in, but conversion has still not happened if (user == null || !user.Identity.IsAuthenticated || !(user.Identity is FormsIdentity)) { return(new MyCMSPrincipal(new MyCMSIdentity((FormsAuthenticationTicket)null))); } var id = (FormsIdentity)_context.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; if (FormsAuthentication.SlidingExpiration) { ticket = FormsAuthentication.RenewTicketIfOld(ticket); } var fid = new MyCMSIdentity(ticket); return(new MyCMSPrincipal(fid)); // not sure what's happening, let's just default here to a Guest }
private void Authenticate() { var context = HttpContext.Current; var actualCookieName = CustomFormsAuthentication.GetActualCookieName(); var ticket = CustomFormsAuthentication.ExtractTicketFromCookie(actualCookieName); if (ticket == null || ticket.Expired) { return; } CustomFormsAuthentication.InitializeUserContext(ticket); var newTicket = ticket; if (CustomFormsAuthentication.SlidingExpiration) { newTicket = FormsAuthentication.RenewTicketIfOld(ticket); } if (newTicket != ticket) { var cookie = CustomFormsAuthentication.GetAuthCookie(actualCookieName, newTicket, true); context.Response.Cookies.Remove(cookie.Name); context.Response.Cookies.Add(cookie); } }
/// <summary> /// 重新分发票据和身份认证的失效时间 /// </summary> /// <param name="context"></param> public static void TryRenewAuthCookieExpires(HttpContext context) { FormsAuthenticationTicket ticket = GetAuthTicket(context); ticket = FormsAuthentication.RenewTicketIfOld(ticket); SetAuthCookie(ticket); }
private static void SignInWithApplication(HttpContextBase context, User user, bool rememberMe) { var durationInHours = rememberMe ? 1680 : 8; HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { cookie = CreateNewTicket(context, user, durationInHours); } else { var oldTicket = FormsAuthentication.Decrypt(cookie.Value); if (oldTicket == null) { cookie = CreateNewTicket(context, user, durationInHours); } else { var oldUser = JsonConvert.DeserializeObject <User>(oldTicket.UserData); if (oldUser != null && oldUser.UserName == user.UserName) { FormsAuthentication.RenewTicketIfOld(oldTicket); } else { cookie = CreateNewTicket(context, user, durationInHours); } } } context.Response.Cookies.Add(cookie); }
public void RenewCurrentUser() { System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = null; authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null && !authTicket.Expired) { FormsAuthenticationTicket newAuthTicket = authTicket; if (FormsAuthentication.SlidingExpiration) { newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket); } string userData = newAuthTicket.UserData; string[] roles = userData.Split(','); System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles); } } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { // look if any security information exists for this request if (HttpContext.Current.User != null) { // see if this user is authenticated, any authenticated cookie (ticket) exists for this user if (HttpContext.Current.User.Identity.IsAuthenticated) { // see if the authentication is done using FormsAuthentication if (HttpContext.Current.User.Identity is FormsIdentity) { // Get the roles stored for this request from the ticket // get the identity of the user FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity; //Get the form authentication ticket of the user FormsAuthenticationTicket ticket = identity.Ticket; // Set Sliding Expiration FormsAuthentication.RenewTicketIfOld(ticket); //Get the roles stored as UserData into ticket //string[] roles = ticket.UserData.Split(','); string[] roles = ticket.UserData.Split('|').Last().Split(','); //Create general principal and assign it to current request HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles); } } } }
/// <summary> /// Renova o ticket de autenticação do usuário logado /// </summary> public static void ManterLogado() { try { FormsAuthentication.RenewTicketIfOld(new FormsAuthenticationTicket(UserInfo.GetUserInfo.CodUser.ToString(), true, 300)); } catch { } }
public string KeepAlive() { if (HttpContext.User.Identity.IsAuthenticated) { var fi = (FormsIdentity)HttpContext.User.Identity; FormsAuthentication.RenewTicketIfOld(fi.Ticket); } return("OK"); }
public void KeepAlive() { var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket ticketOld = null; if (authCookie != null) { ticketOld = FormsAuthentication.Decrypt(authCookie.Value); } FormsAuthenticationTicket ticketNew = null; if (ticketOld == null) { return; } if (FormsAuthentication.SlidingExpiration) { ticketNew = FormsAuthentication.RenewTicketIfOld(ticketOld); } if (ticketNew == null) { return; } var hash = FormsAuthentication.Encrypt(ticketNew); if (ticketNew.IsPersistent) { authCookie.Expires = ticketNew.Expiration; } var authHelper = new AuthorizationTicketHelper(); var token = authHelper.GetToken(); var refreshToken = authHelper.GetRefreshToken(); if (!string.IsNullOrEmpty(token)) { var newhash = this.GetNewHashWithUpdatedToken(refreshToken, ticketNew, token); authCookie.Value = newhash; } else { authCookie.Value = hash; } authCookie.HttpOnly = true; authCookie.Secure = FormsAuthentication.RequireSSL; authCookie.Domain = FormsAuthentication.CookieDomain; authCookie.Path = FormsAuthentication.FormsCookiePath; HttpContext.Current.Response.Cookies.Add(authCookie); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { string strUrlKey = Path.GetFileName(Request.Path); if (strUrlKey.ToLower() != "login.aspx" && strUrlKey.ToLower().EndsWith(".aspx")) { HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = null; bool bolFlag = true; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); FormsAuthentication.RenewTicketIfOld(authTicket); } catch { bolFlag = false; } if (bolFlag && authTicket != null) { UsuarioAutenticado authUser; // if (Context.Session["UsuarioAutenticado"] != null) // authUser = (UsuarioAutenticado) Context.Session["UsuarioAutenticado"]; // else // { authUser = CrearUsuarioAutenticado(authTicket); // HttpContext.Current.Session.Add("UsuarioAutenticado",authUser); //Context.Session["UserPermisos"] = authUser; // } // if (authUser.IsInRole("Administrador") || authUser.CheckAccess(strUrlKey)) { Context.User = authUser; // Context.Session["UsuarioAutenticado"] = authUser; } else { Response.Redirect("/Login.aspx?accessdenied=1&message=" + Server.UrlEncode("El usuario actual no tiene privilegios para realizar la accion solicitada.")); } } else { Response.Redirect("/Login.aspx?accessdenied=1&message=" + Server.UrlEncode("Sus credenciales expiraron.")); } } else { Response.Redirect("/Login.aspx"); } } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (ScriptManager.GetCurrent(this.Page) == null || !ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack) { HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (null == authCookie) { FormsAuthentication.RedirectToLoginPage(); } FormsAuthenticationTicket authTicket = null; try { //assign the ticket to the authentication ticket authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch { FormsAuthentication.RedirectToLoginPage(); } //if ticket is expired or not found terminate the execution and return to the login page to authenticate if (authTicket == null || authTicket.Expired) { FormsAuthentication.RedirectToLoginPage(); } //to store the renewed ticket FormsAuthenticationTicket newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket); if (newAuthTicket.Expiration > authTicket.Expiration) { //create new principal and set the user context Context.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), null); string hash = FormsAuthentication.Encrypt(newAuthTicket); if (newAuthTicket.IsPersistent) { authCookie.Expires = newAuthTicket.Expiration; } authCookie.Value = hash; //authCookie.HttpOnly = true; authCookie.Secure = FormsAuthentication.RequireSSL; if (FormsAuthentication.CookieDomain != null) { authCookie.Domain = FormsAuthentication.CookieDomain; } //store the cookie back into the client machine with latest expiration time Response.Cookies.Add(authCookie); } } }
/// <summary> /// 条件地更新 System.Web.Security.FormsAuthenticationTicket 的发出日期和时间以及过期日期和时间。 /// </summary> /// <param name="userID_g"></param> public static void RenewTicketIfOld(Guid userID_g) { HttpCookie userCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (userCookie != null && string.IsNullOrEmpty(userCookie.Value)) { CreateFormsAuthentication(userID_g); } var authenticationTicket = FormsAuthentication.Decrypt(userCookie.Value); FormsAuthentication.RenewTicketIfOld(authenticationTicket); }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (Context.User != null) { return; } var oldTicket = ExtractTicketFromCookie(Context, FormsAuthentication.FormsCookieName); if (oldTicket == null || oldTicket.Expired) { return; } var ticket = oldTicket; if (FormsAuthentication.SlidingExpiration) { ticket = FormsAuthentication.RenewTicketIfOld(oldTicket); if (ticket == null) { return; } } Context.User = new GenericPrincipal(new FormsIdentity(ticket), new string[0]); if (ticket == oldTicket) { return; } string cookieValue = FormsAuthentication.Encrypt(ticket); var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName] ?? 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; } Context.Response.Cookies.Remove(cookie.Name); Context.Response.Cookies.Add(cookie); }
public string GetFromCookieData() { string sCookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = HttpContext.Current.Request.Cookies[sCookieName]; if (authCookie == null) { //跳转到登录页 try { System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler; if (page != null) { page.Response.Write("<script> top.location.href='" + Helper.GetAppSettings("HomePageUrl") + "';</script>"); } return(null); } catch (Exception e) { return(null); } } FormsAuthenticationTicket authTicket = null; authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket == null) { HttpContext.Current.Response.Clear(); FormsAuthentication.RedirectToLoginPage(); HttpContext.Current.Response.End(); return(null); } if (!authTicket.Expired && FormsAuthentication.SlidingExpiration) { FormsAuthenticationTicket newTicket = FormsAuthentication.RenewTicketIfOld(authTicket); if (authTicket.Expiration != newTicket.Expiration) { string encTicket = FormsAuthentication.Encrypt(newTicket); authCookie.Value = encTicket; authCookie.Expires = newTicket.Expiration; authCookie.Domain = FormsAuthentication.CookieDomain; HttpContext.Current.Response.Cookies.Remove(sCookieName); HttpContext.Current.Response.Cookies.Add(authCookie); } } string sData = authTicket.UserData; sData = OEncryp.Decrypt(sData); return(sData); }
void Application_AuthenticateRequest(object sender, EventArgs e) { //bool enableGzip = this.Request.Headers["Accept-Encoding"] != null ? // this.Request.Headers["Accept-Encoding"].Contains("gzip") : false; //if (enableGzip) //{ // this.Response.Filter = new GZipStream(this.Response.Filter, CompressionMode.Compress); // this.Response.AppendHeader("Content-Encoding", "gzip"); //} if (Context.User == null) { var oldTicket = ExtractTicketFromCookie(Context, FormsAuthentication.FormsCookieName); if (oldTicket != null && !oldTicket.Expired) { var ticket = oldTicket; if (FormsAuthentication.SlidingExpiration) { ticket = FormsAuthentication.RenewTicketIfOld(oldTicket); if (ticket == null) { return; } } string[] roles = new string[] { "Administrator" }; Context.User = new GenericPrincipal(new FormsIdentity(ticket), roles); if (ticket != oldTicket) { string cookieValue = FormsAuthentication.Encrypt(ticket); var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName] ?? 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; } Context.Response.Cookies.Remove(cookie.Name); Context.Response.Cookies.Add(cookie); } } } }
public void HandleFormsAuthenticationTicket(BlogRequest blogRequest, HttpContextBase httpContext, FormsAuthenticationTicket authTicket) { if (authTicket != null) { if (FormsAuthentication.SlidingExpiration) { authTicket = FormsAuthentication.RenewTicketIfOld(authTicket); } // When the ticket was created, the UserData property was assigned a // pipe delimited string of role names. SetHttpContextUser(httpContext, authTicket); } }
private void Application_AuthenticateRequest(object Sender, EventArgs e) { HttpCookie authCookie = this.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (IsValidAuthCookie(authCookie)) { var formsAuthentication = DependencyResolver.Current.GetService <FormsAuthenticationFactory>(); var ticket = FormsAuthentication.Decrypt(authCookie.Value); FormsAuthentication.RenewTicketIfOld(ticket); var authUser = new AuthoringUser(ticket); string[] userRoles = { authUser.UserType }; this.Context.User = new GenericPrincipal(authUser, userRoles); //formsAuthentication.SetAuthCookie(this.Context, ticket); } }
/// <include file='doc\CookielessData.uex' path='docs/doc[@for="CookielessData.CookielessData"]/*' /> public CookielessData() { String name = FormsAuthentication.FormsCookieName; String inboundValue = HttpContext.Current.Request.QueryString[name]; if (inboundValue == null) { inboundValue = HttpContext.Current.Request.Form[name]; } if (inboundValue != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(inboundValue); FormsAuthenticationTicket ticket2 = FormsAuthentication.RenewTicketIfOld(ticket); this[name] = FormsAuthentication.Encrypt(ticket2); } }
/// <summary> /// 设置Cookie的可调过期。 /// </summary> /// <param name="context">HttpContext。</param> /// <param name="ticket">FormsAuthenticationTicket。</param> /// <param name="cookieName">Cookie名称。</param> public static void SlidingExpiration(HttpContext context, FormsAuthenticationTicket ticket, string cookieName) { Check.NotNull(context, "context"); Check.NotNull(ticket, "ticket"); var newAuthenticationTicket = FormsAuthentication.SlidingExpiration ? FormsAuthentication.RenewTicketIfOld(ticket) : ticket; if (newAuthenticationTicket != null) { var cookieValue = FormsAuthentication.Encrypt(newAuthenticationTicket); var authenticationCookie = context.Request.Cookies[cookieName] ?? new HttpCookie(cookieName, cookieValue) { Path = newAuthenticationTicket.CookiePath }; if (ticket.IsPersistent) { authenticationCookie.Expires = newAuthenticationTicket.Expiration; } authenticationCookie.Value = cookieValue; authenticationCookie.Secure = FormsAuthentication.RequireSSL; authenticationCookie.HttpOnly = true; if (!string.IsNullOrEmpty(MainDomain)) { if (HttpContext.Current != null) { var host = "." + HttpContext.Current.Request.Url.Host; if (host.EndsWith(MainDomain, StringComparison.OrdinalIgnoreCase)) { authenticationCookie.Domain = MainDomain; } } else { authenticationCookie.Domain = MainDomain; } } context.Response.Cookies.Remove(authenticationCookie.Name); context.Response.Cookies.Add(authenticationCookie); } }
public void OnAuthorization(AuthorizationContext filterContext) { try { var authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { return; } //Extract the forms authentication cookie var authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket == null) { return; } var concatenatedUserData = authTicket.UserData; var data = concatenatedUserData.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries); if (data.Count() != 1) { return; } var validationToken = data[0]; if (validationToken == null) { //LogHelper.LogException<GlobalIdentityInjectorAttribute>("Validation token is invalid."); } SetPrincipal(filterContext, validationToken); FormsAuthentication.RenewTicketIfOld(authTicket); } catch (Exception ex) { LogHelper.LogException <GlobalIdentityInjectorAttribute>(ex); } }
protected override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); var newTicket = FormsAuthentication.RenewTicketIfOld(ticket); if (newTicket != null && newTicket.Expiration != ticket.Expiration) { string encryptedTicket = FormsAuthentication.Encrypt(newTicket); cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(cookie); } CustomPrincipal.Login(ticket.UserData); } }
public void OnAuthenticateRequest(Object source, EventArgs e) { HttpApplication httpApp = (HttpApplication)source; HttpCookie authCookie = httpApp.Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch { return; } if (authTicket.Expired) { return; } FormsAuthenticationTicket newTicket = FormsAuthentication.RenewTicketIfOld(authTicket); //Generate User from ticket CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <CustomPrincipalSerializeModel>(newTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(newTicket.Name); newUser.UserId = serializeModel.UserId; newUser.Roles = serializeModel.Roles; HttpContext.Current.User = newUser; //If ticket was renewed set new ticket to cookie if (newTicket != authTicket) { string encTicket = FormsAuthentication.Encrypt(newTicket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); httpApp.Context.Response.Cookies.Remove(authCookie.Name); httpApp.Context.Response.Cookies.Add(faCookie); } } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (HttpContext.Current.User != null) { if ((HttpContext.Current.User.Identity.IsAuthenticated)) { //MyPrincipal upro = (MyPrincipal)HttpRuntime.Cache.Get(System.Web.HttpContext.Current.User.Identity.Name); //if ((HttpRuntime.Cache.Get(System.Web.HttpContext.Current.User.Identity.Name) == null)) //{ // // distruggo l'account corrente // System.Web.HttpContext.Current.User = null; // // distruggo il ticket di autenticazione // System.Web.Security.FormsAuthentication.SignOut(); // // abbandono la sessione // if (((System.Web.HttpContext.Current.Session != null))) // { // System.Web.HttpContext.Current.Session.Abandon(); // } // Response.Redirect(((Global)sender).Context.Request.ApplicationPath + "/logoff.aspx?ForceClose=2"); //} //else //{ FormsIdentity id = HttpContext.Current.User.Identity as FormsIdentity; FormsAuthenticationTicket ticket = id.Ticket; FormsAuthentication.RenewTicketIfOld(ticket); HttpContext.Current.User = (MyPrincipal)System.Web.HttpContext.Current.Cache.Get(System.Web.HttpContext.Current.User.Identity.Name); //} } else { if (HttpContext.Current.User != null) { log.Debug(HttpContext.Current.User.Identity.Name); } } } }
public void HandleFormsAuthenticationTicket(BlogRequest blogRequest, HttpContextBase httpContext, FormsAuthenticationTicket authTicket) { if (authTicket != null) { if (FormsAuthentication.SlidingExpiration) { FormsAuthentication.RenewTicketIfOld(authTicket); } // When the ticket was created, the UserData property was assigned a // pipe delimited string of role names. SetHttpContextUser(httpContext, authTicket); } else { httpContext.Response.Cookies.Add(httpContext.Request.GetExpiredCookie(blogRequest.Blog)); //if(blogRequest.RequestLocation != RequestLocation.LoginPage && blogRequest.RequestLocation == RequestLocation.) //{ // RedirectToLogin(blogRequest, httpContext); //} } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { // look if any security information exists for this request if (HttpContext.Current.User != null) { // see if this user is authenticated, any authenticated cookie (ticket) exists for this user if (HttpContext.Current.User.Identity.IsAuthenticated) { var authCookies = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookies != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookies.Value); if (authTicket != null && !authTicket.Expired) { var roles = authTicket.UserData.Split(','); HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles); var newTicket = FormsAuthentication.RenewTicketIfOld(authTicket); string newEncryptedTicket = FormsAuthentication.Encrypt(newTicket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, newEncryptedTicket); HttpContext.Current.Response.Cookies.Add(authCookie); } } // see if the authentication is done using FormsAuthentication //if (HttpContext.Current.User.Identity is FormsIdentity) //{ // // Get the roles stored for this request from the ticket // // get the identity of the user // FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity; // //Get the form authentication ticket of the user // FormsAuthenticationTicket ticket = identity.Ticket; // //Get the roles stored as UserData into ticket // //string[] roles = { }; // string userData = ticket.UserData; // string[] roles = userData.Split(','); // //Create general prrincipal and assign it to current request } } }
private void MvcApplication_AuthenticateRequest(object sender, EventArgs e) { var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) { return; } var app = (HttpApplication)sender; var authTicket = FormsAuthentication.Decrypt(authCookie.Value); var renewedTicket = FormsAuthentication.RenewTicketIfOld(authTicket); if (renewedTicket != authTicket) { string cookieValue = FormsAuthentication.Encrypt(renewedTicket); { if (renewedTicket.IsPersistent) { authCookie.Expires = renewedTicket.Expiration; } authCookie.Value = cookieValue; authCookie.Secure = FormsAuthentication.RequireSSL; authCookie.HttpOnly = true; if (FormsAuthentication.CookieDomain != null) { authCookie.Domain = FormsAuthentication.CookieDomain; } app.Context.Response.Cookies.Remove(authCookie.Name); app.Context.Response.Cookies.Add(authCookie); } } var deserialized = JsonConvert.DeserializeObject <AuthorPrincipalSerializeModel>(authTicket.UserData); app.Context.User = new AuthorPrincipal(deserialized); }
void Application_PreRequestHandlerExecute(object sender, EventArgs e) { var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket objOrigTicket = FormsAuthentication.Decrypt(authCookie.Value); FormsAuthenticationTicket objNewTicket = FormsAuthentication.RenewTicketIfOld(objOrigTicket); if (objNewTicket.Expiration > objOrigTicket.Expiration) { HttpCookie objCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(objNewTicket)); Response.Cookies.Add(objCookie); objOrigTicket = objNewTicket; if (LoginSession.cookieValue.ContainsKey(objOrigTicket.Name)) { LoginSession.cookieValue.Remove(objOrigTicket.Name); } LoginSession.cookieValue.Add(objOrigTicket.Name, objCookie.Value); } } }