Invalidating ASP.NET Forms Authentication tickets server-side

alexjitbit

Alex Yumashev

Posted on July 8, 2019

Invalidating ASP.NET Forms Authentication tickets server-side

Sometimes you need to "log out other user sessions". To prevent cookie replay attacks or - a very common use case - log out other sessions when a user changes their password. ASP.NET does not have a built-in way of doing this, but there's a simple solution.

A FormsAuthenticationTicket object has a built-in property called IssueDate. So you can easily invalidate all forms-auth tickets "older than date X". In our case, it would be "older than last password change"

You can, for example, read the IssueDate property inside Application_AcquireRequestState (in "global.asax") and if the date is "too old" (i.e. older that the user's last password change) log the user out.

Here's some code for you:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    //check if token should be invalidated
    if (User.Identity.IsAuthenticated)
    {
        var lastPswChange = GetPswChangeDate(User.Identity.Name);
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        //psw changed since this auth-token has been issued
        if(authTicket.IssueDate < lastPswChange)
        {
            //log him out
            Logout();
            Response.Redirect("~/User/Login");
            return;
        }
    }
}

private void Logout()
{
    Session.Abandon();
    Session.Clear();
    FormsAuthentication.SignOut();
}

You will have to implement the GetPswChangeDate method yourself.

"Password change date" is just one example. You can have and other date saved in your database next to every user and set it explicitly to whatever value you'd like.

💖 💪 🙅 🚩
alexjitbit
Alex Yumashev

Posted on July 8, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related