[Python] http-only cookie not being added to browser

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am sending my refresh and access tokens as http-only cookies to the frontend of my nextjs application. when I console log the response headers in the frontend, I get the cookies. But they are not being added to the browser.

    My middleware setting on the fastapi code

    origins = [
    config.FRONTEND_ORIGIN
    ]

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


    The endpoint that sends the response

    @auth_router.post("/login", response_model=SuccessLoginResponse, status_code=status.HTTP_200_OK)
    async def login(
    response: Response,
    login_data: LoginRequest,
    request: Request,
    session: AsyncSession = Depends(get_session)
    ):
    IS_PRODUCTION = config.ENV == "production"
    auth_service = get_auth_service(session)
    device_info = request.headers.get("User-Agent", "Unknown Device")

    try:
    tokens = await auth_service.login(login_data, device_info)

    # Set HTTP-only cookies in the response
    response.set_cookie(
    key="refresh_token",
    value=tokens.refresh_token,
    httponly=True,
    max_age=7 * 24 * 60 * 60, # 7 days
    secure=False, # Only set to True in production
    samesite="none",
    )

    response.set_cookie(
    key="access_token",
    value=f"Bearer {tokens.access_token}",
    httponly=True,
    max_age=15 * 60, # 15 minutes
    secure=False, # Only set to True in production
    samesite="none"
    )

    return {
    "success": True,
    "message": "Login successful"
    }
    except UnauthorizedException as e:
    raise HTTPException(
    status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e)) from e
    except Exception as e:
    print(e)
    raise ValidationException(
    detail={
    "message": "Validation error",
    "errors": str(e),
    "documentation_url": "https://api.example.com/docs"
    }
    ) from e


    log from my frontend:

    Object [AxiosHeaders] {
    date: 'Mon, 10 Feb 2025 13:47:16 GMT',
    server: 'uvicorn',
    'content-length': '45',
    'content-type': 'application/json',
    'set-cookie': [
    'refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjM5LCJleHAiOjE3Mzk4MDAwMzZ9.YnELWecBRiLIDuuZS_RUtfwfdRN--GuL7B5XjvGojKY; HttpOnly; Max-Age=604800; Path=/; SameSite=none',
    'access_token="Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjM5LCJleHAiOjE3MzkxOTcwMzd9.3eNjdMx88ax9SpWgcyMkaw3sJCteVfrdUqv7jxTfZVU"; HttpOnly; Max-Age=900; Path=/; SameSite=none'
    ]
    }



    server action for making the request:

    export async function login(
    formData: FormData
    ): Promise<{success: boolean; message: string}> {
    const username = String(formData.get("username"));
    const password = String(formData.get("password"));

    try {
    const response = await axios.post(
    `${API_URL}/auth/login`,
    {username, password},
    {
    withCredentials: true,
    headers: {
    "Content-Type": "application/json",
    },
    }
    );

    console.log(response.headers);

    if (response.status !== 200) {
    throw new Error(response.data?.message || "Login failed");
    }

    console.log("Login successful");
    return {success: true, message: "Login successful"};
    } catch (error) {
    if (axios.isAxiosError(error)) {
    console.error("Login error:", error.response?.data || error.message);
    throw new Error(error.response?.data?.message || "Login failed");
    } else {
    console.error("Unexpected error:", error);
    throw new Error("An unexpected error occurred");
    }
    }

    return redirect("/dashboard");
    }

    Continue reading...

Compartilhe esta Página