-1

I have an angular SPA and .net core 3.1 API to serve the front-end requests.

FE Domain: https://foo.an.fe.mydomain.com:4200 //Also tested in dev environment without port number API Domain: https://foo.an.api.mydomain.com:5001 //Also tested in dev environment without port number

I want to set an HttpOnly cookie from the API in the initial request, and use that cookie in the subsequence requests.

I have used the below code to set the cookie in the backend API.

CookieOptions cookieOptions = new CookieOptions
{
    HttpOnly = true,
    Secure = true,
    Domain = ".mydomain.com",
    Expires = DateTime.Now.AddSeconds(120),
    SameSite = SameSiteMode.None,
    Path = "/"
};

_context.HttpContext.Response.Cookies.Append("myTest", "myValue", cookieOptions);

in the browser, I can see the cookie in the API response. But not available in the Application tab of the developer tool. enter image description here

but in the next request, the browser doesn't add the cookie to the request.

if (_httpContextAccessor.HttpContext.Request.Cookies.TryGetValue("myTest", out var cookie))
{
    _logger.LogInformation($"Cookie Found {cookie}");
}
else
{
    _logger.LogInformation($"Cookie NOT Found");
}

I also have the following CORS configuration in the startup.cs. But I don't believe that's problem.

services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          policy =>
                          {
                              policy.AllowAnyHeader()
                                .AllowAnyMethod()
                                .WithOrigins(Configuration.GetSection("Domains").GetChildren().Select(i => i.Value).ToArray());
                          });
    });

Can anyone point out what I am doing wrong here?

Ash
  • 447
  • 2
  • 6
  • 19
  • last I checked, the port is considered part of the domain. setting a cookie for port 123, will not be sent to port 456. since httponly cookies are managed by the browser, if you want the browser to include the cookie, the domain (including the port) need to match – Edward Apr 12 '22 at 18:31
  • Yes, I tried that but it didn't work either. – Ash Apr 12 '22 at 19:27

1 Answers1

-2

You can not create cookie with HttpOnly option, Javascript API prevents it. It's a server side feature.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies

Therefore you can not add this cookie in the request (from Angular) since it will break "HttpOnly" concept. "HttpOnly" means this cookie is only processable on the server side.

Lounis
  • 597
  • 7
  • 15