Asp.net mvc 4 FormsAuthentication非持久性Cookie在MVC 4应用程序中未过期
我正在尝试使用下面的代码创建表单身份验证cookie。虽然这对持久登录很好,但在我关闭浏览器会话时,非持久cookie不会过期并从浏览器中删除。它仍然保留在浏览器中Asp.net mvc 4 FormsAuthentication非持久性Cookie在MVC 4应用程序中未过期,asp.net-mvc-4,forms-authentication,Asp.net Mvc 4,Forms Authentication,我正在尝试使用下面的代码创建表单身份验证cookie。虽然这对持久登录很好,但在我关闭浏览器会话时,非持久cookie不会过期并从浏览器中删除。它仍然保留在浏览器中 public static void SetAuthenticationCookie(string userName, Role role, bool isPersistent) { string data = role.RoleName; HttpCookie authCookie = FormsAuthentication
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信息的屏幕截图
这里有我遗漏的东西吗?请让我知道我不确定这是否是正确的解决方案。但我发现,即使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);
}
欢迎提出建议或改进
谢谢