Search code examples
authenticationcookiesasp.net-identityaccess-token

How To Logout Using Token Stored In HttpOnly Cookie


I am currently using Microsoft's Identity to help with my Auth in an Asp .NET Web API project. I'm generating a bearer token and storing it in a HttpOnly cookie named AUTH

Since I am not storing anything related to the token in my DB, how do I logout? Before I stored the token in session storage so I simply removed it client side, but now since I am storing the token in a HttpOnly cookie I can't do anything client side.

Do I call a route on the server that responses with a new cookie AUTH and has a empty value? I tried that but the response cookie from logout doesn't seem to replace the HttpOnly cookie, it just creates a session cookie.

This is how I generate the AUTH cookie

context.Response.Cookies.Append("AUTH", accessToken,
                                new Microsoft.Owin.CookieOptions
                                {
                                     HttpOnly = true,
                                     Expires = DateTime.UtcNow.AddMinutes(5)
                                });

This is how I generate the response from the logout route.

var authCookie = new CookieHeaderValue("AUTH", "");
var xsrfCookie = new CookieHeaderValue("XSRF", "");

ActionContext.Response = new HttpResponseMessage();
ActionContext.Response.Headers.AddCookies(new CookieHeaderValue[] { authCookie, xsrfCookie });

return ActionContext.Response;

For some reason, the cookie returned here doesn't override the cookie created with the auth token.

Is this the best strategy to logout a user while storing an auth token in a HttpOnly cookie?


Solution

  • If you are not storing the auth token then you cannot invalid it. So you can force the browser to remove the Cookie from the server. Try adding the Domain and Path. You can also set the Expires to yesterday so the browser removes the cookie as soon as it receives it.

    authCookie.HttpOnly = true;
    authCookie.Expires = DateTime.UtcNow.AddDays(-1);
    authCookie.Domain = "localhost";
    authCookie.Path = "/";
    
    xsrfCookie.Expires = DateTime.UtcNow.AddDays(-1);
    xsrfCookie.Domain = "localhost";
    xsrfCookie.Path = "/";