Python Flask - set-Cookie not received by fetch/ajax request because of Access-Control-Allow-Origin wildcard

Viewed 207

So I'm trying to do the following (inside html template):

  1. Send fetch request to /foo/bar/1, which modifies session object in Flask, and in turn, should send set-Cookie header.

  2. Send fetch request to /foo2/bar2/, which should use new cookie. (which means session object from flask should be updated)

When I check via browser, after request is sent via fetch, it contains set-Cookie (Response cookies are different than request cookies)

But, when I try to perform second fetch request, it still uses old cookies.

If I try to perform fetch manually, via console in browser, it sets cookie correctly, and later uses correct one.

What's more, when I try to print all the headers after first fetch request (via console.log(...response.headers);), it doesn't contain set-Cookie header

my fetch look as following (included in html template, as button.onclick function):

fetch(`/foo/bar/1`, {
    method: 'GET',
    credentials: 'include',
  }).then(function (response, status){
    console.log(...response.headers);
})

Headers that I am receiving is:

['access-control-allow-origin', '*']
['content-length', '1113']
['content-type', 'application/json']
['date', 'Wed, 02 Feb 2022 10:52:56 GMT']
['server', 'Werkzeug/2.0.1 Python/3.9.6']
['vary', 'Cookie']

But Network tab shows there should be another set-Cookie header, which is missing. According to mozilla docs this is to be expected, because of the fragment

Also note that any Set-Cookie response header in a response would not set a cookie if the Access-Control-Allow-Origin value in that response is the "*" wildcard rather an actual origin.

My questions is: How can I change the Access-Control-Allow-Origin from wildcard to actual origin? I've tried setting origins in flask via CORS:

CORS(app, origins=["http://127.0.0.1/:5000"], supports_credentials=True)

But this didn't help, and I'm still getting same Access-Control-Allow-Origin="*"

Another question is: Maybe I'm trying to overdo something there, and there is simpler solution to initial problem? What confuses me, is why when I am doing request manually in browser console, it sets cookie correctly (despite not having set-Cookie header when trying to print the headers, and having wildcard at access-control-allow-origin)

EDIT: apparently even after having correct access-control-allow-origin (non-wildcard), my cookie is still not set and reused in the following requests. My current workaround is just calling endpoint /foo2/bar2/ with extra argument 1 and then calling /foo/bar/1 method, but I'm not happy with that.

0 Answers
Related