reactjsfirebasegoogle-cloud-platformfirebase-authentication

Firebase onAuthStateChanged user returns null when on localhost


I've had a React website running on Firebase for over a year and implemented signInWithRedirect successfully several months ago. However, as of last week, I can no longer log in to my site on localhost despite making no changes to my sign-in code. It appears that the issue resides with the sign-in state observer, onAuthStateChanged, which returns the user as null in my testing.

Again, no changes were made to my sign-in code. I have verified:

I am running Firebase 9.22.2, but I've also tried updating it to 10.4.0 without any change in behavior.

My code:

    const handleGoogleSignIn = async () => {
        await signInWithRedirect(auth, provider);
    };

    onAuthStateChanged(auth, async (user) => {
        if (user) {
            const result = await getRedirectResult(auth);
            if (result) {
                const credential = GoogleAuthProvider.credentialFromResult(result);
                const token = credential.accessToken;
                const user = result.user;
                const expirationTime = user.stsTokenManager.expirationTime;
                const photo = user.photoURL;
                const userName = user.displayName;
                const email = user.email;
            }
        }
    });

    return (
        <Button variant='contained' onClick={handleGoogleSignIn}>
            Log In
        </Button>
    );

When I log in via signInWithRedirect I am properly taken away to log in and then redirected back to my localhost:3000 page, and I enter the onAuthStateChanged properly which I can tell since I've tested putting a console.log(user) at the beginning of that code block. However, when I console.log(user) before the if(user) statement, it returns null every time since last week and it will not enter the if(user) block as it previously did.

Has anyone else had this issue recently? Any suggestions on what else to try?


Solution

  • I contacted Firebase support and after submitting HAR files of the issue with logging into localhost via Firebase, they were able to identify this issue and provide the solution below which works for me.

    Our engineering team has been investigating the issue and has determined that it's due to the Third Party Storage partitioning that's enabled by default in modern web browsers. This partitioning is designed to mitigate the ability of websites to abuse state for cross-site tracking. However, it also affects the emulator's ability to successfully finish the redirect auth flow.

    To fix this behavior on Chrome, you can disable the Third Party Storage partitioning by going to the following settings:

    chrome://flags/#third-party-storage-partitioning

    For Firefox, you can fix the cookie partition behavior by modifying the following setting:

    about:config > network.cookie.cookieBehavior

    Change the value of this setting from 5 to 4.