2

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?

glenho123
  • 579
  • 2
  • 6
  • 21

3 Answers3

5

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);
Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45
4

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();
glenho123
  • 579
  • 2
  • 6
  • 21
0

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

Community
  • 1
  • 1
Joseph
  • 36
  • 3