[Python] Firebase Authentication incorrectly invalidating tokens generated with...

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am developing a system, and I'm currently handling the authentication of users. Here, I'd like users to sign in with their email and password using Firebase. Using the user credentials generated from Firebase Authentication, I'm taking the ID token to pass to the backend for verification before sending to a separate page.

    The problem I'm having now is that the ID token that flows through the frontend just fine, but when the backend receives it and attempts to validate it through auth.verify_id_token(id_token) , I get thrown the auth.InvalidIdTokenError.

    The ID token remains the same throughout the entire process, but it is still invalid. I have checked the duration to find that it wasn't expired, and a few hours ago, when I had tested the verification, this function worked fine and it hasn't been changed since. I've tried to comment out other parts of code that I had worked on but not much success. I've also tried different credentials for service account keys on my Firebase project.

    The code for the frontend, where the token is generated, runs fine without any exceptions.

    try {
    const { emailAddress, password } = data;
    const userCredential = await signInWithEmailAndPassword(
    auth,
    emailAddress,
    password
    );

    // Get the user's ID token
    const idToken = await userCredential.user.getIdToken(true)
    console.log('Firebase ID:',idToken);

    const res = await api.post("/auth/verify_token", { token: idToken, email: emailAddress});

    // Set the temporary token and user ID
    setTempToken(res.data.temp_token);

    } catch (error) {
    console.error("Login Error:", error);
    if (error.code === "auth/user-not-found" || error.code === "auth/wrong-password" || error.code === "auth/invalid-credential") {
    setLoginError("Invalid email or password.");
    } else {
    setLoginError("An error occurred during login.");
    }
    }


    The code on the backend seems to be the problem, but I can't figure out where.

    try:
    data = request.get_json()
    id_token = data.get('token')
    email = data.get('email')
    if not id_token:
    return jsonify({'error': 'Token is required'}), 400

    # Verify the Firebase ID token
    print('Received',id_token)

    decoded_token = auth.verify_id_token(id_token)
    print("decoded")
    uid = decoded_token['uid']

    payload = {
    'uid': uid,
    'email' : email,
    'iat': datetime.utcnow(),
    'exp': datetime.utcnow() + timedelta(minutes=5),
    }

    temp_token = jwt.encode(payload, temp_key, algorithm='HS256')
    return jsonify({
    'message': 'MFA required',
    'temp_token': temp_token, # Include the temporary token
    }), 200

    except auth.InvalidIdTokenError:
    return jsonify({'error': 'Invalid token'}), 401


    I'm out of ideas, any help is much appreciated.

    Continue reading...

Compartilhe esta Página