ASP.Net Core - Cookie Authentication Timing Out


As a learning task, I've created a basic wiki with ASP.Net Core Razor Pages. So far, the experience has been great. One issue I had however is that my authentication (using CookieAuthentication) was timing out way too early and caused issues when I would be in the article editor. My observation was that this timeout seemed to occur within 15-20 minutes. According to the examples I found I thought I had set all of the appropriate timeout's but in fact I missed one and I wanted to share each of the properties I had to set to increase this timeout (there is a cookie timeout, a ticket timeout inside the cookie and then a timeout that is specified inside the SignInAsync method). I had originally thought that the Azure app service I was running it in was resetting but after inspection I realized that wasn't the case (I did however research and implement DataProtection as part of my debugging which additionally will protect the Session's in the site from app pool recycles).

For a primer on manually using CookieAuthentication visit here: Use cookie authentication without ASP.NET Core Identity

Finally... here are the lines of code where I set timeout's to alleviate this issue.

Startup.cs => public void ConfigureServices

    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
        o.LoginPath = new PathString("/Login");
        o.AccessDeniedPath = new PathString("/Unauthorized");
        o.SlidingExpiration = true;                    
        o.ExpireTimeSpan = TimeSpan.FromMinutes(60);
        o.Cookie.Expiration = TimeSpan.FromMinutes(60);                   

Login.cshtml.cs => This is the method where the user initiates the sign in

    new AuthenticationProperties
        ExpiresUtc = DateTime.UtcNow.AddMinutes(60),
        IsPersistent = true,
        AllowRefresh = true

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.

PNW Greg
PNW Greg - Tuesday, April 12, 2022

Thanks!! This is just what I needed. I thought my problem was session timeouts and couldn't figure out why changing the session timeout value didn't help. Finding this answer was like looking for a needle in a haystack! By the way, using Cookie.Expiration now returns an error: "OptionsValidationException: Cookie.Expiration is ignored, use ExpireTimeSpan instead." I deleted that line, and everything else worked.