dochoffiday
dochoffiday

Reputation: 5575

FormsAuthentication.SignOut() not working after changing the CookieDomain

In the web.config, we had the following:

<authentication mode="Forms">
  <forms loginUrl="~/login" timeout="43200" slidingExpiration="true" name=".PX" />
</authentication>

We have since updated it to this:

<authentication mode="Forms">
  <forms loginUrl="~/login" timeout="43200" slidingExpiration="true" name=".PX" enableCrossAppRedirects="true" domain="[websitename].com" />
</authentication>

The problem is, users who are already logged in are no longer signed out when we call FormsAuthentication.SignOut().

Instead of just callign FormsAuthentication.SignOut(), I now do the following, but it still isn't signing out currently logged in users:

private static void SignOut(HttpContextBase context)
{
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, FormsAuthentication.CookieDomain, true);
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, FormsAuthentication.CookieDomain, false);
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, null, true);
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, null, false);

    // clear cookies server side
    context.Request.Cookies.Clear();

    context.Session.Abandon();
    FormsAuthentication.SignOut();
}

private static void RemoveCookie(HttpContextBase context, string name, string path, string domain, bool httpOnly)
{
    context.Response.Cookies.Add(new HttpCookie(name, "NoCookie")
    {
        Path = path,
        Domain = domain,
        Secure = false,
        Shareable = false,
        HttpOnly = httpOnly,
        Expires = DateTime.Now.AddDays(-1d)
    });
}

Upvotes: 3

Views: 81

Answers (1)

dochoffiday
dochoffiday

Reputation: 5575

In FormsAuthentication.SignOut() there is a call the removes all of the previous cookies from the Response: context.Response.Cookies.RemoveCookie(FormsCookieName); (https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/FormsAuthentication.cs#L421)

Changing the order of everything seems to fix the issue:

private static void SignOut(HttpContextBase context)
{
    context.Session.Abandon();
    FormsAuthentication.SignOut();

    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, FormsAuthentication.CookieDomain, true);
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, FormsAuthentication.CookieDomain, false);
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, null, true);
    RemoveCookie(context, FormsAuthentication.FormsCookieName, FormsAuthentication.FormsCookiePath, null, false);

    // clear cookies server side
    context.Request.Cookies.Clear();
}

Upvotes: 2

Related Questions