Search code examples
cookiesasp.net-identitysession-cookiesidentity

AspNetCore: OpenId Cookies always show expires=1969-12-31 even with IsPersistent=true and ExpireTimeSpan set


Using ASPNETCORE OpenId authentication middleware and Cookie middleware. I always see that cookies from OpenId authentication are set to expire at 1969-12-31 (in Chrome debugger). I assume this means the cookies are SESSION cookies; I want to make them persistent cookies so the user will be prompted to login less frequently. So I added the ExpireTimeSpan and IsPersistent=true as suggested in other posts, but I still see that my cookie Expires is 1969-12-31.

What am I doing wrong?

enter image description here

        services.AddAuthentication(options =>
        {
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddAzureAd(options =>
        {
            Configuration.Bind("AzureAd", options);
        })
        .AddCookie(p =>
        {
            p.ExpireTimeSpan = TimeSpan.FromDays(30);
            p.SlidingExpiration = true;
        });

        services.Configure<AuthenticationProperties>(props =>
        {
            props.IsPersistent = true;
            props.ExpiresUtc = new DateTimeOffset(DateTime.Now, TimeSpan.FromDays(30));
        });

Solution

  • Got helped on the aspnetcore security forum, and arrived at the following solution:

            .AddCookie(p =>
            {
                p.SlidingExpiration = true;
                p.Events.OnSigningIn = (context) =>
                {
                    context.CookieOptions.Expires = DateTimeOffset.UtcNow.AddDays(30);
                    return Task.CompletedTask;
                };
            });
    

    I also implemented a Logout page (call to AuthenticationHttpContextExtensions.SignOutAsync(HttpContext)) to give the user more control over cookie lifetimes.