Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormsAuthentication.SignOut Not Working With Custom-Domain Cookie

Title should say it all.

Here's the code to set the cookie:

// snip - some other code to create custom ticket
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encodedTicket);
httpCookie.Domain = "mysite.com";
httpContextBase.Response.Cookies.Add(httpCookie);

Here's my code to signout of my website:

FormsAuthentication.SignOut();

Environment:

  • ASP.NET MVC 3 Web Application

  • IIS Express

  • Visual Studio 2010

  • Custom domain: "http://localhost.www.mysite.com"

So when i try and log-off, the cookie is still there. If i get rid of the httpCookie.Domain line (e.g default to null), it works fine.

Other weird thing i noticed is that when i set the domain, Chrome doesn't show my cookie in the Resources portion of developer tools, but when i dont set the domain, it does.

And secondly, when i actually create the cookie with the custom domain, on the next request when i read in the cookie from the request (to decrypt it), the cookie is there, but the domain is null?

I also tried creating another cookie with the same name and setting the expiry to yesterday. No dice.

What's going on? Can anyone help?

like image 805
RPM1984 Avatar asked Oct 18 '11 02:10

RPM1984


1 Answers

I believe if you set the domain attribute on the forms element in you web.config, to the same as the one in your custom cookie, it should work. (EDIT: that approach won't work because the SignOut method on FormsAuthentication sets other flags on the cookie that you are not, like HttpOnly) The SignOut method basically just sets the cookie's expiration date to 1999, and it needs the domain to set the right cookie.

If you can't hardcode the domain, you can roll your own sign out method:

private static void SignOut()
{
    var myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
    myCookie.Domain = "mysite.com";
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    HttpContext.Current.Response.Cookies.Add(myCookie);
}

An authentication cookie is just a plain cookie; so you would remove it the same way you would any other cookie: expire it and make it invalid.

like image 115
vcsjones Avatar answered Oct 06 '22 12:10

vcsjones