Search code examples
c#authenticationcookiesasp.net-coresession-cookies

How to reduce cookie size in ASP.NET Core (something similar to using reference mode)?


I am implementing an ASP.NET Core web application that uses cookie and WS-Federation authentication (it uses the cookie if it's there and works, otherwise it asks the identity provider for a SAML token if the user is signed in).

I have this set up fine in a Web API project in .NET. For cookie authentication, I use System.IdentityModel.Services.SessionAuthenticationModule to help. More specifically, it has the IsReferenceMode property which I set to true, thus allowing the cookie to be stored in a server-side cache throughout the session. This allows just a reference to the cookie to be passed between the client and server which helps reduce the size of the cookie.

Obviously this is not directly supported in ASP.NET Core since System.IdentityModel is incompatible. I'm wondering if there's something similar I can do.

I've seen similar questions asked here and here, but neither really help me.

Edit: This article on session state from the Microsoft docs and this blog article by Jan Hajek seem like they could provide an answer for me.


Solution

  • You could use a simple MemoryCacheTicketStore that implements ITicketStore and configure your cookie like so:

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
        options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ApplicationScheme;
    })
    .AddIdentityCookies(options => options.ApplicationCookie.Configure(configureOptions =>
        {
            configureOptions.SessionStore = new MemoryCacheTicketStore(ApplicationSettings.Current.AuthenticationTimeOut);
        })
    );
    

    This is taken from a GitHub sample, please have a look at it.