r/FastAPI • u/No-Question-3229 • Jul 20 '24
Question Why Does Setting Cookies Not Work
Im having an issue setting my auth cookies for some reason. I dont know why fast api wont set these cookies.
async def set_cookies():
# Get cookie header
# Used to tell auth server if it should set the login cookies
set_auth_cookies = request.headers.get("set-auth-cookies")
print(f"set-auth-cookies header: {set_auth_cookies}")
print(f"Type: {type(set_auth_cookies)}")
print(f"Boolean value: {bool(set_auth_cookies)}")
if set_auth_cookies != None and bool(set_auth_cookies) == True:
response.set_cookie(key="LIF_USERNAME", value=username, domain=".lifplatforms.com", path="/")
response.set_cookie(key="LIF_TOKEN", value=token, domain=".lifplatforms.com", path="/")
print("set auth cookies")
Ive tried timing to make sure the cookies are being set before the request completes and it looks like thats good. Ive even tried using 'await' on the set cookie functions but complains I cant use await on NoneType. I dont know what else could be causing the issue.
Full Source Code: https://github.com/Lif-Platforms/Lif-Auth-Server/blob/107-make-login-route-set-cookies/src/auth_server.py#L160
3
Upvotes
View all comments
Show parent comment
3
u/Top-Information7943 Jul 21 '24
Both approaches work fine, but for security, cookies are preferred for web auth. The issues you are experiencing with cookies on the frontend is because of CORS (Cross-Origin Resource Sharing).
You will need to add the frontend URL to your FastAPI's
originsapp. See examples below:The example above is from FastAPI docs https://fastapi.tiangolo.com/tutorial/cors/