Set a browser cookie from backend code
Using Python/FastAPI and ES5 fetch. Works on localhost as well.
CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=config.ALLOWED_ORIGINS, # these can include localhost:<port>, etc
allow_credentials=True, # must have :)
allow_methods=["*"],
allow_headers=["*"] # can be a list like ["Accept", "Access-Control-Allow-Credentials", "Authorization", "WithCredentials", "Content-Type", "X-CSRF-Token", "SelectedGroup", "Allow-Credentials", "Set-Cookie"], but ["*"] works as well
)
Cookie setting
@router.post("/signin", response_model=MySpecialResponse)
async def signin(request: Request, form_data: SigninModel, response: Response):
# ...
response.set_cookie(
key="yum",
value=token,
httponly=True,
secure=True, # https
samesite="lax", # To be able to access it in iframes as well
domain=config.AUTH_COOKIE_DOMAIN,
path='/',
max_age=int(expires_delta.total_seconds() - 3600),
)
JS caller
const res = await fetch(`${WEB}/signin`, {
credentials: 'include', // must-have :)
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password
})
})
Don’t forget that secure
should be True
if samesite='none'
. The cookies won’t be accessible from Javascript (that’s the whole point), due to httponly=True
.
Some resources:
- https://stackoverflow.com/questions/73962743/fastapi-is-not-returning-cookies-to-react-frontend
- https://stackoverflow.com/questions/15914744/javascript-document-cookie-always-returns-empty-string
samesite="lax"
versussamesite="strict"
: https://stackoverflow.com/questions/59990864/what-is-the-difference-between-samesite-lax-and-samesite-strict- https://stackoverflow.com/questions/73730172/response-header-set-cookie-doesnt-store-cookies-in-browser
- Very comprehensive explanation: https://stackoverflow.com/questions/46288437/set-cookies-for-cross-origin-requests