Cookie Expiration value is ignored in the CookieAutenticationHandler

Viewed 1158

I've been trying to set an expiration time to my session cookie. So at first, I've configured my Cookie handler in this way:

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options => 
{
    options.Cookie.Expiration = TimeSpan.FromSeconds(3600);
})
.AddOpenIdConnect(...

Although it seemed simple it is not. The cookie was always created as session (not persisted).

I've been exploring the CookieAuthenticationHandler and I found this:

protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
    if (user == null)
    {
        throw new ArgumentNullException(nameof(user));
    }

    properties = properties ?? new AuthenticationProperties();

    _signInCalled = true;

    // Process the request cookie to initialize members like _sessionKey.
    await EnsureCookieTicket();
    var cookieOptions = BuildCookieOptions();
    ...
}

The surprising thing is that in the method BuildCookieOptions sets to null the expiration that I have configured in the startup:

private CookieOptions BuildCookieOptions()
{
    var cookieOptions = Options.Cookie.Build(Context);
    // ignore the 'Expires' value as this will be computed elsewhere
    cookieOptions.Expires = null;

    return cookieOptions;
}

It says that the 'Expires' value will be computed elsewhere.

Finally, I have seen in other post that when using the RemoteAuthenticationHandler like the one used by OpenId, the handler triggers an OnTicketRecived event where the expiration can be set by implementing this event in the configuration of the OpenId handler:

.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = "Cookies";
    options.ClientId = "client";

    options.Events.OnTicketReceived = async (context) => 
    {
        context.Properties.ExpiresUtc = DateTime.UtcNow.AddSeconds(3600);
        context.Properties.IsPersistent = true;
    };

But, why this Expiration value is absolutely ignored? Why CookieAuthenticationOptions let me set this property but the first thing the handler does is set it to null? Does this property any use?

Or simply am I missing something?

0 Answers
Related