[Python] Issue: Firebase Auth + FastAPI Token Verification Fails After Sign-In

Discussão em 'Python' iniciado por Stack, Maio 31, 2025.

  1. Stack

    Stack Membro Participativo

    Context: I'm building a User Auth with Firebase Authentication (Google Sign-In) on the frontend(HTML,CSS,JS) and using a FastAPI backend for token verification.

    Frontend uses Firebase to authenticate and retrieve an idToken

    Backend (FastAPI) is set up with a router:

    in fastapi side main.py

    app = FastAPI()

    app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8080"], # your frontend origin
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],)

    @app.middleware("http")
    async def add_custom_headers(request: Request, call_next):
    response: Response = await call_next(request)
    response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
    #response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
    response.headers["Cross-Origin-Resource-Policy"] = "cross-origin"
    return response


    app.include_router(api_router)
    app.mount("/static", StaticFiles(directory="static"), name="static")


    in auth_router.py

    router = APIRouter()
    security=HTTPBearer()

    # init firebase
    cred = credentials.Certificate('/workspace/draftflow-b7b11-firebase-adminsdk-fbsvc-77f9fcd8a6.json')
    firebase_admin.initialize_app(cred)

    @router.get("/verify-token")
    def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    try:
    # decode and verify the token
    decoded_token = auth.verify_id_token(credentials.credentials)
    uid = decoded_token.get("uid")
    email = decoded_token.get("email")
    name = decoded_token.get("name")
    return {
    "status": "success",
    "uid": uid,
    "email": email,
    "name": name
    }
    except Exception as e:
    print("Token verification failed:", e)
    raise HTTPException(status_code=401, detail="Invalid token")



    in frontend side in auth.html i use firebaseauth.js

    // firebase config is initialized
    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    auth.languageCode = "en";
    const db = getFirestore(app);
    const googleProvider = new GoogleAuthProvider();

    function handleRedirectResult(){
    getRedirectResult(auth)
    .then(async (result) => {
    // If no result (user canceled sign-in), exit early
    if (!result) {
    console.log("No redirect result.");
    return;
    }

    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;
    const user = result.user;
    const idToken = await user.getIdToken();
    localStorage.setItem("jwtID", idToken);
    window.location.href = "/home";

    })
    .catch((error)=>{
    console.log('Error handnling reidrect result: ', error);
    })
    }


    function signInWithGoogle() {
    signInWithRedirect(auth, googleProvider)
    .catch((error) => {
    console.error('Error during sign in:', error);
    //handleAuthError(error);
    });
    }
    // ✅ Google Sign-in Button Listener
    document.addEventListener('DOMContentLoaded', ()=>{
    handleRedirectResult();
    const googleBtn = document.getElementById("googleLoginBtn");
    if (googleBtn) {
    googleBtn.addEventListener("click", signInWithGoogle);
    }
    });



    in router/init.py

    app.include_router(auth_router, prefix="/auth", tags=["Authentication"])


    ❌ The Problem:

    Firebase Redirect to google signin page when I sign In using my google aoount it redirects to the same auth page.

    Tech Stack: Frontend: HTML, CSS, JS + Firebase Auth (Google Sign-In)

    Backend: FastAPI + Firebase Admin SDK

    I have been trying various methods for solving but nothing worked.

    Continue reading...

Compartilhe esta Página