【问题标题】:FormsAuthentication non persistent Cookie is not getting expired in MVC 4 ApplicationFormsAuthentication 非持久性 Cookie 在 MVC 4 应用程序中没有过期
【发布时间】:2014-02-05 01:21:07
【问题描述】:

我正在尝试使用以下代码创建表单身份验证 cookie。虽然这适用于持久登录,但当我关闭浏览器会话时,非持久 cookie 不会过期并从浏览器中删除。它仍然存在于浏览器中。

public static void SetAuthenticationCookie(string userName, Role role, 
bool isPersistent)
{
 string data = role.RoleName;
 HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName,isPersistent);
 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
 FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(
 ticket.Version, ticket.Name, ticket.IssueDate,ticket.Expiration,
 ticket.IsPersistent,data);
  authCookie.Value = FormsAuthentication.Encrypt(newticket);
  HttpContext.Current.Response.Cookies.Add(authCookie);            
}

这是表单身份验证的 web.config 条目

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" cookieless="UseCookies" name=".OneClick" 
  protection="All" slidingExpiration="true" timeout="43200" />
</authentication> 

这里是浏览器的cookie信息截图

这里有什么我遗漏的吗?请告诉我

【问题讨论】:

    标签: asp.net-mvc-4 forms-authentication


    【解决方案1】:

    我不确定这是否是正确的解决方案。但我发现,即使 cookie 到期设置为之前的日期时间,表单身份验证票证到期也是从 web.config 设置的,使其行为类似于持久 cookie。所以我尝试将 1 分钟设置为 cookie 和票证到期,这使得 cookie 和票证在 1 分钟的超时期限后到期。

    即使非持久性 cookie 应该在浏览器会话结束后过期。由于某种原因,此 cookie 会一直保留到表单身份验证 cookie 过期为止。

    这里是解决方案。

    public static void SetAuthenticationCookie(string userName, Role role, 
                      bool isPersistent)
    {
      string data = role.RoleName;
      HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, 
      isPersistent);            
    
      if (!isPersistent)
      {
         authCookie.Expires = DateTime.Now.AddMinutes(30);
      }
    
     FormsAuthenticationTicket ticket=FormsAuthentication.Decrypt(authCookie.Value);        
     FormsAuthenticationTicket newticket=
     new FormsAuthenticationTicket(ticket.Version,ticket.Name, ticket.IssueDate,
     authCookie.Expires, ticket.IsPersistent, data);            
     authCookie.Value = FormsAuthentication.Encrypt(newticket);
     HttpContext.Current.Response.Cookies.Add(authCookie);            
    }
    

    欢迎提出建议或改进。

    谢谢

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 2011-04-21
      相关资源
      最近更新 更多