15

During migration of an ASPNetCore 1.1 Project to ASPNetCore 2.0, we stumbled upon a Problem with the Cookie-AuthN and its SessionStore.

ASP.NET Core 1 allowed us to do something like that:

public void ConfigureServices(...) {
    Services.AddDistributedSqlServerCache(...);
    Services.AddSingleton<DistributedCookieSessionStore>(); /// SQL based store
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) {
    var cookieOptions = app.ApplicationServices.GetRequiredService<IOptions<CookieAuthenticationOptions>>().Value;
    cookieOptions.SessionStore = app.ApplicationServices.GetRequiredService<DistributedCookieSessionStore>();

    app.UseCookieAuthentication(cookieOptions);
}

Messy, but doing its Job.

Now with ASP.NET Core 2 app.UseAuthentication() does not have a signature allowing to modify the options, and I am not able to use DI, to get a hold of the session store.

TGlatzer
  • 5,815
  • 2
  • 25
  • 46

1 Answers1

23

After long search I came accross this discussion https://github.com/aspnet/Security/issues/1338 where they mentioned IPostConfigureOptions interface. I put that together and this works for me:

1) Implement interface IPostConfigureOptions<CookieAuthenticationOptions>

public class PostConfigureCookieAuthenticationOptions : IPostConfigureOptions<CookieAuthenticationOptions>
{
    private readonly ITicketStore _ticketStore;

    public PostConfigureCookieAuthenticationOptions(ITicketStore ticketStore)
    {
        _ticketStore = ticketStore;
    }

    public void PostConfigure(string name, CookieAuthenticationOptions options)
    {
        options.SessionStore = _ticketStore;
    }
}

2) Register this implementation to the container in Startup.ConfigureServices method

services.AddSingleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>();

Brian MacKay
  • 31,133
  • 17
  • 86
  • 125
pvasek
  • 1,086
  • 11
  • 11
  • 1
    Thank you so much for this! Major help! – Brian MacKay Dec 03 '18 at 14:43
  • 1
    I wish I could vote this up 10x. This is the only way I could get a SessionStore working with ASP.NET Identity 2.x + IdentityServer when securing resources with OIDC on the local IDP. Thank you! – mikeo Apr 13 '19 at 23:06
  • @pvasek services.AddSingleton, PostConfigureCookieAuthenticationOptions>(); ==> i think should not use AddSingleton here – Anh Tú Jun 09 '21 at 04:18