简体   繁体   中英

ASP.Net delete/expire session cookies

We have a number of internal company ASP.Net applications. All use Forms Authentication and all are session based...

What I am trying to do is when a user logs out of one application he/she is logged out of all applications.

I have some logic that iterates the cookies collection. I can see all the other ASP.Net applications but I can not remove them.

Im currently using the following logic:

// expire all asp.net app tickets
        string[] allDomainCookes = HttpContext.Current.Request.Cookies.AllKeys;

        foreach (string domainCookie in allDomainCookes)
        {
            if (domainCookie.Contains("ASPXAUTH"))
            {
                var expiredCookie = new HttpCookie(domainCookie) { Expires = DateTime.Now.AddDays(-1) };
                HttpContext.Current.Response.Cookies.Add(expiredCookie);
            }
        }
        HttpContext.Current.Request.Cookies.Clear();

For some reason they are not being removed. I know they are all there because I have written them to the page. They are just not being removed....is this because these are session cookies?

Also I should add they are all sub-domains of the some domain so ownership should not be an issue?

Actually...I've just found the problem. I need to specify the domain as well

string[] allDomainCookes = HttpContext.Current.Request.Cookies.AllKeys;

    foreach (string domainCookie in allDomainCookes)
    {
        if (domainCookie.Contains("ASPXAUTH"))
        {
            var expiredCookie = new HttpCookie(domainCookie) { 
                  Expires = DateTime.Now.AddDays(-1),
                  Domain = ".mydomain"
            };
            HttpContext.Current.Response.Cookies.Add(expiredCookie);
        }
    }
    HttpContext.Current.Request.Cookies.Clear();

try this code ..works for me

            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            HttpContext.Current.Response.Cookies.Add(cookie1);
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            HttpContext.Current.Response.Cookies.Add(cookie2);

Cookies only works in the same domain. If it's cross domain, you need another solution. Here is another article about Asp.net cookie

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM