0

I'm attempting to set a cookie for my ASP.NET Core Web API project in localhost, but the cookie only gets sent through the response header and not set in the browser. I have tried setting

withcredentials: true

in the cookie, but that did not work.

Here is the code of the controller:

string token = "Some string";
var cookieOptions = new CookieOptions()
    {
        IsEssential = true,
        Expires = DateTime.Now.AddMinutes(30),
        Secure = true,
        HttpOnly = true,
        SameSite = SameSiteMode.None
    };

Response.Cookies.Append("XSRF_Auth", token, cookieOptions);

Here is a snippet of the network information for that response:

Response Information

Also, my program.cs file looks like this:

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
string[] origins = {"https://localhost:4200"};

builder.Services.AddCors();

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins(origins));

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

I'm not receiving any errors and the cookie fails to get set in all browsers. I'm using a self-signed certificate for ssl and I'm using .NET Core 6.0. I usually never had issues in previous versions of .NET Core, but this issue is very odd to me.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Trayvon Como
  • 1
  • 1
  • 2
  • How do you check that the cookie is not set in your browser? – GoodboY Apr 11 '22 at 20:40
  • I check by looking at the browser storage **F12 > Application > Cookies** in chrome and I even went as far as calling a request that returns `Request.Cookies["XSRF_Auth"];`. All of the third-party cookies I receive are set successfully, but I'm not even able to set an auto-generated session cookie. – Trayvon Como Apr 11 '22 at 20:53
  • Seems like your app configuration is okay since the response has a `set-cookie` header set on your screenshot. Are you sure that this cookie is not overwritten by another request? – GoodboY Apr 11 '22 at 21:12
  • No, no worries. I'm going to start a brand new project and try to add a cookie right off the bat. If all goes well, I'll add the rest of my code and try to pinpoint the issue. – Trayvon Como Apr 11 '22 at 22:22
  • @TrayvonComo Hi, I'm facing same situation. Have you solved this problem? If so, could you post your solution please? – takeyourcode May 30 '22 at 10:08

1 Answers1

0

When you setHttpOnly = true, cookies only appear in the request header and cannot be accessible by the client script.

Fouad
  • 131
  • 1
  • 11