Set / update expiration on aspxauth and asp.net_sessionid cookies

若如初见. 提交于 2019-12-21 22:17:25

问题


I am wondering if there is a way you can setup your .NET application to set and update the expiration time of the aspxauth and asp.net_sessionid cookies in the browser?

From what I see, the cookies' expiration dates are something like 1/1/0001 telling the browser to keep them until the browser closes (I've observed this using Chrome). I'd like to set an explicit time, but, I will need to update that time on every request.

I am attempting to do this with some code like :

var timeoutMins = Session.Timeout;
if (Response.Cookies.Count > 0)
{
   foreach (string s in Response.Cookies.AllKeys)
   {
       if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
       {
           Response.Cookies[s].Expires = DateTime.Now.AddMinutes(timeoutMins);
       }
   }
}

I tried doing this in the global.asax End_Request event, although this doesn't seem to be a good place since it fires several times per page and you dont have access to the sessionstate timeout; further it only triggers on login and logout, so basically I can set it once but I can never update it. This causes my users to be logged out 15 minutes after login even if they have been active.

It seems like there would be some setting somewhere to tell .net to handle this? I know this is a strange request but it is a security requirement on this project so I'm trying to make it work!


回答1:


It looks like not many people are trying to do what I'm doing, but for the record, I added code to the application end request to find the cookies in the request and recreate them in the response with the appropriate expiration time :

var timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["myTimeoutConfigSetting"]);    

foreach (var cookey in Request.Cookies.AllKeys)
{
  if (cookey == FormsAuthentication.FormsCookieName || cookey.ToLower() == "asp.net_sessionid")
  {
      var reqCookie = Request.Cookies[cookey];                                      

      if (reqCookie != null)
      {
          HttpCookie respCookie = new HttpCookie(reqCookie.Name, reqCookie.Value);
          respCookie.Expires = DateTime.Now.AddMinutes(timeout);

          Response.Cookies.Set(respCookie);
      }
  }
}



回答2:


Here is a nice way to do it

http://www.andreas-kraus.net/blog/increase-aspnet-authentication-membership-cookie-timeout/

and this one http://forums.asp.net/p/1158239/1920541.aspx#1920541



来源:https://stackoverflow.com/questions/10439483/set-update-expiration-on-aspxauth-and-asp-net-sessionid-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!