Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie cannot be read by script

I'm trying to read a cookie from a browser by the following Javascript code using the js-cookie package. However, the cookie is not being read.

import Cookies from 'js-cookie';
var cookie_name = 'cookie';
var cookie = Cookies.get(cookie_name);
console.log(cookie);

The cookie is created using the below Python code that utilizes Flask.

response.headers.add('Access-Control-Allow-Headers', 'Content-Type, text/plain')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
response.headers.add('Access-Control-Allow-Credentials', 'true')
response.set_cookie(key='cookie',
                value=payload,
                domain='<url>')

The Flask app has the following parameters

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = False

Above I've turned off the HttpOnly flag so my script should be able to read the cookie. I also cannot see the cookie using console.log(document.cookie) in the browser. Is there any reason why my JS code can't read the cookie?

like image 292
Black Avatar asked Nov 07 '22 21:11

Black


1 Answers

If you can't see the cookie in the browser console it means that it either isn't being set or that it is being set with HTTP only.

SESSION_COOKIE_HTTPONLY should only affect the session cookie set by Flask, it looks like you are trying to set a different cookie entirely.

I would:

  1. Confirm that the cookie is really being set (you can check this via dev tools)
  2. If it is being set, and somehow being set with HTTP only turned on, change your code:

...

response.set_cookie(key='cookie', value=payload, domain=<url>, httponly=False)
like image 143
Susanne Peng Avatar answered Nov 10 '22 01:11

Susanne Peng