DEV Community

Alex Yumashev
Alex Yumashev

Posted on • Originally published at jitbit.com

2 2

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay