Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

421
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda