Cookies are not being appended to the page with the following code, I have tried adding IsEssential to the options but it did not work. Using Asp.Net Core 3.1 Razor Pages. Here's most of my startup.cs and appending cookie code.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddRazorPages();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSignalR();
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseRequestLocalization();
app.UseStaticFiles();
app.UseCookiePolicy();
app.useAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
Adding Cookie
string key = "Cookie";
var cookieValue = Request.Cookies[key];
if(cookieValue == null)
{
string value = "true";
var cookieOptions = new CookieOptions()
{
Path = "/",
HttpOnly = false,
IsEssential = true,
Expires = DateTime.Now.AddDays(1),
};
HttpContext.Response.Cookies.Append(key, value, cookieOptions);
}
Recommendations were to add IsEssential to override the CookiePolicy but that didn't solve anything. Devtools applications show only .AspNetCore.Identity.Application and .AspNetCore.Antiforgery cookies.
Edit: Solved by changing
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
to
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});