如何使用FastAPI为跨域请求设置cookie

Pel*_*leg 5 javascript python cookies axios fastapi

我有一个基于 FastAPI 的应用程序,它作为网站的后端,当前部署在具有外部 IP 的服务器上。前端位于另一个开发人员处,暂时在本地托管。工作之初我们遇到了CORS问题,使用我在网上找到的如下代码解决了这个问题:

from fastapi.middleware.cors import CORSMiddleware
...
app.add_middleware(
    CORSMiddleware,
    allow_origins=['http://localhost:3000'],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Run Code Online (Sandbox Code Playgroud)

添加内容允许 Frontend 正确发出请求,但由于某种原因,设置为发送(并在 Swagger UI 中正常工作)的 cookie 未在 Frontend 中设置。客户端看起来像:

axios({
            method: 'POST',
            baseURL: 'http://urlbase.com:8000',
            url: '/login',
            params: {
                mail: 'zzz@zzz.com',
                password: 'xxxxxx'
            },
            withCredentials: true
        }).then( res => console.log(res.data) )
        .catch( err => console.log(err))
Run Code Online (Sandbox Code Playgroud)

enc*_*nce 7

在FastAPI中设置和读取cookie可以通过使用该类来完成Request

设置cookierefresh_token

from fastapi import Response

@app.get('/set')
async def setting(response: Response):
    response.set_cookie(key='refresh_token', value='helloworld', httponly=True)
    return True
Run Code Online (Sandbox Code Playgroud)

设置httponly=True确保 cookie 不能被 JS 访问。这对于刷新令牌等敏感数据非常有用。但如果您的数据不是那么敏感,那么您可以忽略它。

读取cookie

from fastapi import Cookie

@app.get('/read')
async def reading(refresh_token: Optional[str] = Cookie(None)):
    return refresh_token
Run Code Online (Sandbox Code Playgroud)

您可以在此处的 FastAPI 文档中找到有关使用 cookie 作为参数的更多信息。


小智 0

在 FastAPI 中,您可以通过设置 cookie response.set_cookie

from fastapi import FastAPI, Response

app = FastAPI()


@app.post("/cookie-and-object/")
def create_cookie(response: Response):
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return {"message": "Come to the dark side, we have cookies"}
Run Code Online (Sandbox Code Playgroud)

应该注意的是,这些不是安全会话,您应该使用类似itsdangerous 的东西来创建加密会话。

响应似乎未发送的请求;您应该确保设置了 cookie 对哪些 URL 有效的选项。默认情况下,它们通常/意味着一切,但是您的系统可能会使用 CORS 设置将它们设置为特定情况。