简体   繁体   中英

CookiePolicyOptions interfering with localization cookie in Blazor server-side app

I have a Blazor server-side and I have the following cookie policy options set up:

services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

The app also implements cookie localization as described in this MS article .

However, the problem is that with the above policy options, the localization cookie is not being created.

If I change the policy options to (or remove them completely):

services.Configure<CookiePolicyOptions>(options =>
{
    options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
});

The localization cookie is created and localization works as expected. So the original options are interfering with the localization cookie.

A sample Blazor project experiencing this problem is found in this GitHub repo .

Is there a solution/workaround in which I have the original cookie policy options (required for consent) and also a working localization cookie?

Two changes must be done do get it working:

Change the cooking policy options as follows:

services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
    options.Secure = CookieSecurePolicy.Always;
});

Change the code where the culture is set as follows:

[Route("[controller]/[action]")]
public class CultureController : Controller
{
    public IActionResult Set(string culture, string redirectUri)
    {
        if (culture != null)
        {
            HttpContext.Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(
                    new RequestCulture(culture, culture)), 
                    new CookieOptions {
                        Expires = DateTimeOffset.UtcNow.AddYears(1),
                        IsEssential = true,
                        Path = "/",
                        HttpOnly = false,
                    }
            );
        }

        return LocalRedirect(redirectUri);
    }
}

IsEssential is the most important property as it tells the cookie to bypass any cookie policy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM