You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI集成fastapi-session后前端无法存储Cookie问题求助

FastAPI + fastapi-session 前端Cookie存储问题解决

问题场景

使用FastAPI搭配fastapi-session实现会话管理,Postman测试接口可正常生成并返回Cookie,但对接前端HTML/JS时,前端无法存储Cookie,手动用JS设置Cookie也无效。

核心原因及解决步骤

  • Fetch请求未携带凭证:前端fetch默认不会携带跨域凭证,必须显式配置credentials: 'include',否则浏览器会忽略后端返回的Cookie。
  • Cookie跨域配置不匹配:需要确保fastapi-session的CookieSameSite属性设置为'Lax'或'None'(HTTPS环境),secure属性需和运行环境匹配(HTTP开发环境设为False,HTTPS生产环境设为True)。
  • 接口返回值异常:原代码直接返回response对象给前端,会导致响应格式异常,影响浏览器处理Cookie。

修改后的代码片段

Python/FastAPI部分

# fastapi
app = FastAPI(
    title="API",
    description=description,
    version="1.0.0",
    openapi_tags=tags_metadata,
)
# 生产环境建议替换为具体前端域名,不要用*
origins = ["*"]
app.add_middleware(CORSMiddleware,
                   allow_origins=origins,
                   allow_credentials=True,
                   allow_methods=["*"],
                   allow_headers=["*"], )

# 配置fastapi-session的Cookie,适配跨域场景
from fastapi_session.backends.implementations import InMemoryBackend
from fastapi_session.cookie import CookieBackend

cookie = CookieBackend(
    cookie_name="session_id",
    secret_key="your-secret-key-here",
    same_site="Lax",  # 跨域场景若用HTTPS可设为None,需配合secure=True
    secure=False,     # 开发环境HTTP设为False,生产HTTPS设为True
    httponly=True     # 建议开启,防范XSS攻击
)
backend = InMemoryBackend()

@app.get("/", tags=["Root"], response_model=Result,
         responses={
             **responses,
             200: {
                 "description": "Successfully created new session",
                 "content": {
                     "application/json": {
                         "example": {'status_code': '0', 'status_message': 'Success',
                                     'data': "hi admin. How can i help you"}
                     }
                 },
             },
         })
async def root(response: Response, auth: str = Header(None)):
    if auth:
        authenticate = hmac.compare_digest(auth, "abc")
        if authenticate:
            session = uuid1()
            SessionCreation(session)
            data = SessionData(authorized=authenticate, session_id=session)
            await backend.create(session, data)
            cookie.attach_to_response(response, session)
            # 返回正常业务数据,不要返回response对象
            return {"status_code": "0", "status_message": "Success", "data": "hi admin. How can i help you"}
        else:
            return JSONResponse(status_code=401, content="Unauthorized!")
    else:
        return JSONResponse(status_code=404, content={"message": "Missing Header"})

JavaScript部分

fetch(url, {
    method: "GET",
    mode: "cors",
    credentials: 'include', // 关键配置:携带跨域凭证
    headers: new Headers({
        "auth": "abc",
        "Content-Type": "application/json; charset=UTF-8",
    }),
})
.then(() => {
    alert(document.cookie);
});

内容的提问来源于stack exchange,提问作者new_dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:27:23