【问题标题】:Unable to set httpOnly cookie between Heroku and Netlify + cloudflare无法在 Heroku 和 Netlify + cloudflare 之间设置 httpOnly cookie
【发布时间】:2020-07-28 20:44:38
【问题描述】:

我有以下问题。我正在尝试设置 httpOnly cookie,但没有任何反应。我花了几个小时试图解决这个问题,但我不知道发生了什么......我的架构如下:

后端:Heroku 上托管的 Python fast-api,地址为 https://api.mysuperdomain.com

前端:GatsbyJs 托管在 Netlify 上,地址为 https://mysuperdomain.com

当我从 React 组件调用登录请求时:

  const handleSubmit = async (e) => {
    e.preventDefault()
    const config = {
      headers: {
        crossDomain: true,
        withCredentials: true,
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
    const requestBody = {
      username: emailRef.current.value,
      password: passwordRef.current.value
    }

    try {
      const data = await axios.post('https://api.mysuperdomain.com/login', qs.stringify(requestBody), config)

我从后端收到带有标头 set-cookie 的响应:

set-cookie: Authorization="Bearer somethinghere"; Domain=.mysuperdomain.com; expires=Tue, 28 Jul 2020 20:40:32 GMT; Max-Age=1800; Path=/; SameSite=lax

很遗憾,在浏览器存储中我看不到这个 cookie。

我的后端(API)通过以下方式设置 cookie:

@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")

    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": form_data.username}, expires_delta=access_token_expires
    )

    token = jsonable_encoder(access_token)

    response = JSONResponse({'status': 'authenticated'})
    response.set_cookie(
        key="Authorization",
        value=f"Bearer {token}",
        domain=".mysuperdomain.com",
        httponly=True,
        max_age=1800,
        expires=1800,
    )
    return response

我的 DNS 记录在 Cloudflare 中,后端的 CNAME 记录被代理:

Typ    Name  Content                                        TTL    Proxy status 
CNAME  api   limitless-starfish-something.herokudns.com     Auto   Proxied

SSL/TLS 加密模式是灵活的(加密浏览器和 Cloudflare 之间的流量)。 Heroku 的后端没有 SSL 证书,因此我设置了灵活的 SSL/TLS 加密模式。

也许它与上面的配置有某种关系?

【问题讨论】:

    标签: reactjs heroku netlify setcookie fastapi


    【解决方案1】:

    我认为这是因为您没有向应用添加 CORS 中间件,在 FastAPI 中,allow_credentials 默认设置为 bool = False。但您可以轻松更改。

    首先你需要从fastapi.middlewares导入CORSMiddleware

    from fastapi.middleware.cors import CORSMiddleware
    

    然后我们可以在我们的应用中添加一个中间件

    app.add_middleware(
        CORSMiddleware,                         
        allow_credentials=True,
    )
    

    您还可以使用 CORSMiddleware 添加来源和所有其他内容,更多相关信息请查看FastAPI-CORS out。

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2020-01-06
      • 1970-01-01
      • 2021-03-30
      • 2020-04-27
      • 2020-03-19
      相关资源
      最近更新 更多