authenticationcookiesopenid-connectglobalization

Using Microsoft.AspNetCore.Authentication.OpenIdConnect Prevents Language Selection of CookieRequestCultureProvider


Using the MS OpenIdConnect middleware locks the culture cookie (CookieRequestCultureProvider) when localizing the application. The app switches languages without the authentication middleware, but stops when reintroduced.

I'm sure I'm missing something simple.

Configuration:

public void ConfigureServices(IServiceCollection services)
    //...
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    //...
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.LoginPath = OpenIdConfig.SigninUrl;
        options.Cookie.Name = string.Format(".{0}.Cookies", OpenIdConfig.AppName);
        options.Cookie.HttpOnly = false;
        options.Cookie.SameSite = SameSiteMode.None;
        options.Cookie.MaxAge = TimeSpan.FromDays(OpenIdConfig.CookiesTimeOut);
        options.ExpireTimeSpan = TimeSpan.FromDays(OpenIdConfig.CookiesTimeOut);

        if (_env.IsDevelopment())
        {
            options.Cookie.Domain = OpenIdConfig.SharedDomain;
        }
        options.CookieManager = new ChunkingCookieManager()
        {
            ChunkSize = 4090
        };
        options.Events = new CookieAuthenticationEvents
        {
            OnValidatePrincipal = async x => await Task.CompletedTask
        };
    }).AddOpenIdConnect(...)
}

Here is the Langage select action:

public async Task<IActionResult> SetLanguage(string culture, string returnUrl)
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return await Task.FromResult(LocalRedirect(returnUrl));
}

I've tried several culture cookie and auth cookie configurations, any help would be appreciated.


Solution

  • You need to use HTTP and also set the SameSite policy to lax:

    options.MinimumSameSitePolicy = SameSiteMode.Lax;
    

    To complement this answer, I wrote a blog post that goes into more detail about this topic: Debugging cookie problems in ASP.NET Core.