Conditionally set sliding expiration time on authentication cookies in ASP.NET Core

Legogris
Cacti pins
Published in
2 min readNov 16, 2016
This was one of those days.

Using ASP.NET Core’s cookie middleware for authentication is pretty neat. Once set up properly, it allows us to seamlessly share authentication between our existing 4.6 MVC OWIN application and our new fancy Core SPA.

One key feature is the SlidingExpiration option. This automatically sends a refreshed authentication cookie once the existing cookie is half-way to expiration, ensuring that the user stays logged in for the duration of their session.

However, this might not be what we want for all requests. When continuously polling for updates, we do not want to reset the token. The approach to solve this is the same as for 4.6: Just remove the cookie from the response. This turned out to be quite trickier to get right than expected. The straight-forward solution that worked with 4.6 doesn’t apply here.

The first part is easy: Figure out which requests to separate. We have two options:

  1. Let the client decide (e.g. by query string, request content, HTTP header)
  2. Let the server decide (e.g. separate routes)

We went with #2 and implemented it as a FilterAttribute we would tag our actions with:

We just add an item to the HttpContext to indicate to our middleware to act accordingly.

Basically, the cookie middleware appends its cookie right before headers are sent to the client. Core doesn’t allow us to remove cookies that are already set; we can only append or expire cookies — which would immediately unauthorize the user. So we need to rewrite the Set-Cookie headers. Furthermode, the cookie middleware adds its cookie at the very last moment, so we need to register our handler really late in the pipeline.

OnStarting is the new name for OnSendingHeaders since RC2.

Middleware ordering is important here: Since OnStarting callbacks get called LIFO, our cookie-removing callback needs to be added before we add CookieAuthentication.

So there you have it. Core is still a work in progress and I would hope that we can get a more natural way to remove cookies in the future.

--

--

Legogris
Cacti pins

Consultant & Co-founder @ Cacti AB. Httpster by day, decentralization enthusiast by night.