4

I can't figure out why the cookie is not being stored. The cookie is sent in the Response Header and then it doesn't show up in the dev tools. My configuration looks like this:

vite.config.ts

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api/*': {
        target: 'http://localhost:4242',
        changeOrigin: true,
      },
    },
  },
});

main.py

@app.post("/api/v1/token")
async def login_for_access_token(response: Response, loginemail: str = Form(...), loginpassword: str = Form(...), db: Session = Depends(get_db)):
    user = authenticate_user(db, loginemail, loginpassword)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Falsche Email Adresse oder Passwort.",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.email}, expires_delta=access_token_expires
    )

    response.set_cookie(key='access_token', value=access_token, httponly=True, domain='http://localhost:5173', path='/')
    return {'detail': 'Anmeldung erfolgreich.'}

then the cors settings in the main.py

origins = [
    "http://localhost:5173",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

I tried various different settings with response.set_cookie but nothing works. I am using fetch and tried to include credentials but the cookie is just lost after being sent from the backend.

pmo42
  • 66
  • 5

1 Answers1

1

The response never gets sent because you return a dictionary instead of the response. If you also want to include the detail, set the body of the response.

@app.post("/api/v1/token")
async def login_for_access_token(response: Response, loginemail: str = Form(...), loginpassword: str = Form(...), db: Session = Depends(get_db)):
    user = authenticate_user(db, loginemail, loginpassword)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Falsche Email Adresse oder Passwort.",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.email}, expires_delta=access_token_expires
    )

    response.set_cookie(key='access_token', value=access_token, httponly=True, domain='http://localhost:5173', path='/')
    response.body = response.render(json.dumps({'detail': 'Anmeldung erfolgreich.'}))
    return response
SimonUnderwood
  • 469
  • 3
  • 12