【发布时间】:2018-05-19 20:34:39
【问题描述】:
我正在尝试使用 Python Flask 后端在浏览器中设置 cookie,但是,当我们调用 set cookie 函数时,我无法观察到浏览器保存的 cookie。以下是我目前对它应该如何工作的理解:
- Cookie 只是键值对,它们可能具有使它们持久化的过期时间,否则它们会在浏览器关闭时过期
- 要设置 cookie,只需在响应中使用 set-cookie 标头即可。为此,我调用了烧瓶响应对象的 set_cookie 方法。
- 浏览器应该自动保存cookie并遵循过期规则(在浏览器收到的响应中可以观察到set_cookie头)
在 Angular HttpClient 中发出请求
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers, withCredentials: true });
const request_data = {'username': this.username, 'password': this.password};
this.http.post('http://localhost:8080/token', request_data, options)
在 Python Flask 中设置 cookie
g.response = make_response()
time = datetime.datetime.now() + datetime.timedelta(days=30)
g.response.set_cookie("auth_token", auth.token, expires=time)
return g.response
浏览器中的纯文本响应
HTTP/1.1 200 OK
set-cookie: auth_token=7253f2fa43d7584741dcf8972dea8f; Expires=Fri, 05-Jan-2018 01:33:30 GMT; Path=/
vary: Origin
access-control-allow-credentials: true
access-control-allow-origin: http://127.0.0.1:4200
content-type: application/json
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Cache-Control: no-cache
Content-Length: 58
Server: Development/2.0
Date: Wed, 06 Dec 2017 01:33:30 GMT
探索的其他想法和帖子:
- 尝试同时使用 Safari 和 Chrome,并在两者中收到相同的结果。我还验证了浏览器允许使用 cookie。
- $http doesn't send cookie in Requests
- Cookie is not set in browser
- How do I SET a Cookie (header) with XMLHttpRequest in JavaScript?
问题:
如何让浏览器保存 cookie 以便在当前会话中使用?
【问题讨论】:
-
你熟悉
localStorage和sessionStorage吗? -
您好,我希望在此处存储会话令牌。根据我在网上看到的情况,cookie 是最安全的方法。我引用的一篇文章说“永远不要在本地存储中存储访问令牌,该存储区域非常容易受到 XSS 攻击”stormpath.com/blog/token-auth-spa。如果您认为还有另一种安全的方法,请告诉我。谢谢!