[Python] FastAPI authentication token in not appearing in the frontend [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I am using google oauth for authentication in my my application. But the cookie does not appear in the cookies in the browser. I am returning the redirect response from the callback and setting the cookie in it. I would love to know of any other secure way how to the the token in the frontend.

    @router.get("/google/login")
    async def google_login():
    flow = Flow.from_client_secrets_file(
    CLIENT_SECRETS_FILE,
    scopes=SCOPES,
    redirect_uri=settings.google_redirect_uri
    )
    authorization_url, state = flow.authorization_url(
    access_type='offline',
    include_granted_scopes='true'
    )

    return RedirectResponse(authorization_url)

    @router.get("/google/callback")
    async def google_callback(
    code: str,
    response: Response,
    state: str = None,
    session: AsyncSession = Depends(get_session)
    ):
    response.headers['set-auth-cookies'] = 'true'
    try:
    flow = Flow.from_client_secrets_file(
    CLIENT_SECRETS_FILE,
    scopes=SCOPES,
    redirect_uri=settings.google_redirect_uri
    )

    # Use the authorization server's response to fetch the OAuth 2.0 tokens
    flow.fetch_token(code=code)
    # Get the ID token from OAuth2 flow
    credentials = flow.credentials
    id_info = id_token.verify_oauth2_token(credentials.id_token, requests.Request(), settings.google_client_id)
    user: UserCreate = UserCreate(name=id_info.get('name'), email=id_info.get('email'), password="", is_verified=True)
    user_auth = AuthenticationService(session, user, google_user=True)
    if await user_auth.user_exists() and await user_auth.user_verified():
    print("User exists and is verified")
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)
    headers = {'Authorization': f'Bearer {access_token}'}
    response.set_cookie(
    key="access_token",
    value=access_token,
    httponly=True,
    domain='localhost'
    )
    print("You are in google callback 1")
    print(response)
    print(response.status_code)
    print(response.headers)
    # print(response.cookies)
    return RedirectResponse(url="http://localhost:5173/auth-success", headers=headers, status_code=302)
    elif await user_auth.user_exists() and not await user_auth.user_verified():
    print("User exists and is not verified")
    await user_auth.set_verified()
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)
    headers = {'Authorization': f'Bearer {access_token}'}
    response.set_cookie(
    key="access_token",
    value=access_token,
    httponly=True,
    domain='localhost'
    )
    return RedirectResponse(url="http://localhost:5173/auth-success", headers=headers, status_code=302)
    else:
    print("User does not exist")
    await user_auth.create_user()
    access_token_expires = timedelta(minutes=30)
    access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)
    headers = {'Authorization': f'Bearer {access_token}'}
    response.set_cookie(
    key="access_token",
    value=access_token,
    httponly=True,
    domain='localhost'
    )
    return RedirectResponse(url="http://localhost:5173/auth-success", headers=headers, status_code=302)

    except Exception as e:
    raise HTTPException(status_code=400, detail=f"Invalid id_token: {str(e)}")



    I created the response object for the redirect link and attached the token to it. But still it is not appearing in the frontend.

    Continue reading...

Compartilhe esta Página