cookiescorssamesite

why SameSite Lax sends the cookie to POST XHR request to cross origin when credentials: 'include' is set?


As I read on the internet, SameSite=Lax can't send the cookie with POST XHR request to cross-origin. I tried to replicate this behavior

I hosted frontend on :8080

    <button onclick="callPostApiCrossSite()">Call POST CrossSite</button>
    <script>
        const crossSiteUrl = "http://localhost:8081"
        const optionsForPost = {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json'
            },
        }
        var x = fetch(`${crossSiteUrl}/crossSite`, optionsForPost)
        console.log(x);
    </script>
http.createServer(function (request, response) {
    try {
        // log the request on console
        console.log(request.url);
        // Dispatch
        dispatcher1.dispatch(request, response);
    } catch (err) {
        console.log(err);
    }
}).listen(8081);

    
dispatcher1.on("options", "/crossSite", function(request, response) {
    console.log("option is called");
    response.writeHeader(200, { 
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET,POST" ,
        "Access-Control-Allow-Headers": "content-type",
        "Access-Control-Allow-Origin": "http://localhost:8080",
    });
    response.end();
})
dispatcher1.onPost("/crossSite", function (request, response) {
    console.log("8081 Post Cookie: ", request.headers["cookie"])
    response.writeHeader(200, { "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "http://localhost:8080",
    "Access-Control-Allow-Credentials": "true", });    
    response.write('{"Statue": "OK"}')
    response.end();
});

I had a cookie in the browser with sameSite=Lax. I from the front end (hosted on :8080) sent a post request (by clicking button) to :8081 with the POST HTTP method. Then, instead of the browser throwing a CORS error, it enabled the response for the front end. I was able to log the cookie and the browser didn't throw any CORS error.

Is this the expected behavior, Can anybody explain?


Solution

  • A request is cross-site only if origin and target have

    The port does not matter at all. Therefore, a request from http://localhost:8080 to http://localhost:8081 is same-site (but cross-origin).