I’m working on a FastAPI app with Google OAuth login. When users authenticate, I try to set a cookie with their auth token, but the cookie never shows up in the browser. I’m using a redirect response after the OAuth callback and trying to attach the cookie to it. The redirect works fine but the cookie just disappears. Are there better ways to pass authentication tokens to the frontend securely?
@app.get("/auth/google")
async def start_google_auth():
oauth_flow = Flow.from_client_secrets_file(
SECRETS_FILE,
scopes=["openid", "email", "profile"],
redirect_uri=config.oauth_callback_url
)
auth_url, session_state = oauth_flow.authorization_url(
access_type='offline',
include_granted_scopes='true'
)
return RedirectResponse(auth_url)
@app.get("/auth/callback")
async def handle_oauth_callback(
auth_code: str,
resp: Response,
db: AsyncSession = Depends(get_db)
):
try:
oauth_flow = Flow.from_client_secrets_file(
SECRETS_FILE,
scopes=["openid", "email", "profile"],
redirect_uri=config.oauth_callback_url
)
oauth_flow.fetch_token(code=auth_code)
creds = oauth_flow.credentials
token_info = id_token.verify_oauth2_token(
creds.id_token,
requests.Request(),
config.google_client_id
)
user_data = UserSchema(
full_name=token_info.get('name'),
email=token_info.get('email'),
password="",
verified=True
)
auth_service = UserAuthService(db, user_data, from_google=True)
if await auth_service.user_exists():
if not await auth_service.is_verified():
await auth_service.verify_user()
else:
await auth_service.register_user()
token_expiry = timedelta(minutes=45)
jwt_token = generate_jwt_token(
data={"email": user_data.email},
expires_delta=token_expiry
)
resp.set_cookie(
key="jwt_token",
value=jwt_token,
httponly=True,
domain='localhost'
)
return RedirectResponse(
url="http://localhost:3000/dashboard",
status_code=302
)
except Exception as error:
raise HTTPException(
status_code=400,
detail=f"OAuth error: {str(error)}"
)
I’m setting up the Response object and adding the cookie before the redirect, but it’s not working. What could be going wrong here?