Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

420
Vistas
Unable to set httpOnly cookie between Heroku and Netlify + cloudflare

I have the following problem. I am trying to set httpOnly cookie and nothing happens. I spent a few hours trying to solve this issue and I have no idea what is going on... My architecture is the following:

Backend: Python fast-api hosted on Heroku, available at https://api.mysuperdomain.com.

Frontend: GatsbyJs hosted on Netlify, available at https://mysuperdomain.com

When I call login request from React component:

  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)

I get response from my backend with headers, 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

unfortunately in browser storage I cannot see this cookie.

My backend(API) sets the cookie in the following way:

@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

My DNS records are within the Cloudflare, and CNAME record for backend is proxied:

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

SSL/TLS encryption mode is Flexible (Encrypts traffic between the browser and Cloudflare). Backend at Heroku has no SSL Certificate therefore I set flexible SSL/TLS encryption mode.

Maybe it is somehow related to above config?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I think this happens because you didn't add a CORS middleware to your app, in FastAPI, allow_credentials is set to bool = False in default. But you can change that easily.

First you need to import CORSMiddleware from fastapi.middlewares

from fastapi.middleware.cors import CORSMiddleware

Then we can add a middleware to our app

app.add_middleware(
    CORSMiddleware,                         
    allow_credentials=True,
)

Also you can add origins and all other stuff with CORSMiddleware, for more related info check FastAPI-CORS out.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda