【发布时间】:2022-11-15 00:54:41
【问题描述】:
我第一次实施使用 HttpOnly Cookie 登录身份验证.就我而言,它是在用户调用 login 方法时创建的Python 服务使用 fastapi 和 uvicorn。
我已经阅读了 MDN 文档来实现 expires 属性,因此,浏览器会在时间到期时删除此 cookie。
我已经使用 http.cookies 和 Morsel 在 Python 中实现了 Cookie 以应用HttpOnly像这样的财产:
from http import cookies
from fastapi import FastAPI, Response, Cookie, Request
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
mytoken = 'blablabla'
def getUtcDate():
sessionDate = datetime.now()
sessionDate += timedelta(minutes=2)
return sessionDate.strftime('%a, %d %b %Y %H:%M:%S GMT')
@app.get('cookietest')
def getCookie(response: Response):
cookie = cookies.Morsel()
cookie['httponly'] = True
cookie['version'] = '1.0.0'
cookie['domain'] = '127.0.0.1'
cookie['path'] = '/'
cookie['expires'] = getUtcDate()
cookie['max-age'] = 120
cookie['samesite'] = 'Strict'
cookie.set("jwt", "jwt", mytoken)
response.headers.append("Set-Cookie", cookie.output())
return {'status':'ok'}
这样做,当我调用“cookietest”端点时,Cookies 在浏览器中看起来正确,证据是:
如图所示,cookie 在 Expires / Max-Age 中有一个过期日期时间:“Wed, 12 Oct 2022 11:24:58 GMT”,登录后 2 分钟(如果用户在 14:05 登录: 00,cookie 在 14:07:00 到期)
我的问题是超过过期时间时,任何浏览器都不会删除 cookie,所以这让我很困惑。如果我等了几分钟,然后向另一个端点(如http://127.0.0.1:8000/info)发出请求,cookie 仍然存在于 http 标头中。
问题是什么?我做错了什么?我正在阅读很多关于 cookie 存储和过期的文档,但我看不到任何关于这个问题的信息。
非常感谢问候
已编辑:问题已解决
正如Chris 所说,使用 FastApi 中的 set_cookie 方法解决了问题。
我仍然想知道为什么 MSD 文档表明日期格式必须是特定的格式,不会导致浏览器删除 Cookie,但指示以秒为单位的时间可以正常工作。
@app.get("/cookietest")
async def cookietest(response: Response):
response.set_cookie(
key='jwt',
value=getToken(),
max_age=120,
expires=120,
path='/',
secure=False,
httponly=True,
samesite="strict",
domain='127.0.0.1'
)
return {"Result": "Ok"}
【问题讨论】:
-
只是让您知道您可以使用
Response对象的set_cookie方法创建 cookie,如 this answer 中所述。另请参阅相关的FastAPI documentation 和Starlette documentation。 -
您可以在
set_cookie方法中设置expires标志,该方法采用一个整数来定义cookie 过期前的秒数。例如,如果您希望 cookie 在创建后 2 分钟内过期,请使用expires=120。 -
好的,我使用 fastapi 中的 set_cookie 方法更改了我的代码,现在可以使用了,但是,为什么 MDN 文档说 Expires 使用格式如下的 DateTime “Expires: Wed, 21 Oct 2015 07:28:00 GMT”?
标签: python-3.x cookies fastapi uvicorn cookie-httponly