2

I'm writing my first ASP.NET 7 app and I'm confused about how cookies are set up. I've read various blogs and tutorials and have gleaned the following information:

Configure the cookie policy and authentication in Program.cs like this:

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

 

builder.Services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

And add this middleware:

app.UseCookiePolicy(new CookiePolicyOptions { Secure = CookieSecurePolicy.Always, HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always }) ;

From what I can see the cookie policy options are being set twice, with different options? Should it only be done in one place with all the options? Is there a difference in doing it in one place or the other?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Germgh0st
  • 41
  • 3
  • Cookies are stored on the client machine in the user temp space. The cookies are obtained from the server and are returned to client in the response. Then when new request are made to server you add the cookies to you do not have to establish new credentials with the server every timer you send a request. Your first block is Add an Authentication for a new cookie. The second block is using an existing cookie. – jdweng May 15 '23 at 14:44
  • @jdweng 'Your first block is Add an Authentication for a new cookie. The second block is using an existing cookie.' - Could you expand on that please? At this point no cookie has actually been created, that is done later. I am adding the cookie policy here. – Germgh0st May 15 '23 at 14:57
  • If no cookie has been created then how can you add a cookie : AddCookie() – jdweng May 15 '23 at 15:27
  • @jdweng - That is adding the cookie authentication scheme. – Germgh0st May 15 '23 at 15:39
  • Then it should be : https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.cookieextensions.addcookie?view=aspnetcore-7.0#microsoft-extensions-dependencyinjection-cookieextensions-addcookie(microsoft-aspnetcore-authentication-authenticationbuilder) – jdweng May 15 '23 at 15:51
  • @jdweng have you actually read the question I posted?? – Germgh0st May 15 '23 at 16:39
  • 1
    @jdweng I believe this is purely related to which mechanism(s) to use when setting up via `program.cs` as the options appear to exist in both mechanisms, not the actual read/write of cookies. – EvilDr May 15 '23 at 16:41

0 Answers0