Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX request not sending cookies (NET 5)

For testing purposes, two web apps are set up, a "client" app (localhost) and a server app (Azure web app). The client sends an AJAX request to the server and receives a cookie in response. Then it makes another AJAX call to the server, but there's no cookie in the request, it's missing.

Here's the server configuration (CORS setup; https://localhost:44316 is my "client" URL):

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => {
            o.AddPolicy("policy1", builder =>
                builder.WithOrigins("https://localhost:44316")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("policy1");

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Here's the first controller, returning the cookie:

[Route("api/[controller]")]
[ApiController]
public class AController : ControllerBase
{
    [HttpPost]
    public IActionResult Post()
    {
        var cookieOptions = new CookieOptions
        {
            HttpOnly = true,
            Expires = DateTime.Now.AddMinutes(10),
            SameSite = SameSiteMode.None
        };
        Response.Cookies.Append("mykey", "myvalue", cookieOptions);

        return Ok();
    }
}

Here's the second controller, which should receive the cookie (but it doesn't):

[Route("api/[controller]")]
[ApiController]
public class BController : ControllerBase
{
    [HttpPost]
    public IActionResult Post()
    {
        var x = Request.Cookies;

        return Ok(JsonConvert.SerializeObject(x));
    }
}

And here's the calling script from the "client" (first and second call, respectively):

function Go()
{
    $.ajax({
        url: 'https://somewebsite.azurewebsites.net/api/a',
        type: 'post',
        xhrFields: {
            withCredentials: true
        },
        success: function (data, textStatus, jQxhr)
        {
            console.log(data);
        },
        error: function (jqXhr, textStatus, errorThrown)
        {
            console.log(errorThrown);
        }
    });
}

function Go2()
{
    $.ajax({
        url: 'https://somewebsite.azurewebsites.net/api/b',
        type: 'post',
        xhrFields: {
            withCredentials: true
        },
        success: function (data, textStatus, jQxhr)
        {
            console.log(data);
        },
        error: function (jqXhr, textStatus, errorThrown)
        {
            console.log(errorThrown);
        }
    });
}

Does anyone have an idea what could be the problem here?

like image 431
Marko Avatar asked Dec 05 '25 13:12

Marko


2 Answers

As this document said :

Cookies that assert SameSite=None must also be marked as Secure

But you didn't, so use this instead:

var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Expires = DateTime.Now.AddMinutes(10),
                SameSite = SameSiteMode.None,
                Secure = true
            };

And this is my test result:

enter image description here

like image 98
Tiny Wang Avatar answered Dec 08 '25 04:12

Tiny Wang


I quite like the style of what you are doing here in terms of an SPA getting cookies from an API. Some recommendations below, based on experience at dealing with these issues.

PROBLEM

You are calling from the browser to an API in a different domain, meaning the cookie is third party and modern browsers will drop it aggressively.

  • Web Origin: localhost:44316
  • API Domain: myazurewebapp.com

SameSite=None is the theoretical solution from standards docs but these often do not explain current browser behaviour:

  • You have to set the Secure property, as Jason Pan says
  • But it will still not work in the Safari browser and maybe some others
  • Expect cross site cookies to be dropped in all browsers in the near future

SOLUTION

The preferred option is to design hosting domains so that only first party cookies are used, and many software companies have done this. It can be done by running the API in a child or sibling domain of the web origin:

  • Web Origin: www.example.com
  • API Domain: api.example.com

On a developer PC you can do this simply by updating your hosts file. Note also that you can run web and API components on different ports and they will remain same site:

127.0.0.1 localhost www.example.com api.example.com
:1        localhost

The browser will then still be making CORS requests, but will consider the cookie issued by the API to be in the same site as the web origin. You can then also change the cookie settings to use SameSite=strict, for best security.

FURTHER INFO

At Curity we have published some recent articles on web security that are closely related to your question, since secure cookies used in OpenID Connect security have also had to deal with dropped cookie problems:

  • Code
  • Articles
like image 39
Gary Archer Avatar answered Dec 08 '25 04:12

Gary Archer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!