firebase / firebase-js-sdk

Firebase Javascript SDK
https://firebase.google.com/docs/web/setup
Other
4.76k stars 874 forks source link

Firebase onAuthStateChanged user returns null when on localhost #7716

Open Code-Hex opened 8 months ago

Code-Hex commented 8 months ago

Operating System

macOS 13.6 on arm64

Browser Version

Chrome/118.0.5993.88,118.0.5993.96 Firefox/118.0.2, Safari 17.0 (18616.1.27.111.22, 18616)

Firebase SDK Version

9.12.0,9.22.0-9.22.2,9.23.0,10.5.0

Firebase SDK Product:

Auth

Describe your project's tooling

React and Vite, use firebase hosting and .web.app domains

We specified auth domain is like develop-hoge.web.app on localhost

Describe the problem

As stated on this URL, we're facing an issue where authentication doesn't work when using signInWithRedirect on localhost, causing significant development hurdles. After trying various solutions, it appears to be related to third-party cookie restrictions. Disabling this restriction in Firefox seemed to allow development as before, but unfortunately, it didn't work in Chrome. https://stackoverflow.com/questions/77270210/firebase-onauthstatechanged-user-returns-null-when-on-localhost

Steps and code to reproduce issue

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

onAuthStateChanged(auth, async (user) => {
    console.log({ user }) // always be null
    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>
);
hsubox76 commented 8 months ago

I think it may be related to this: https://firebase.google.com/docs/auth/web/redirect-best-practices

I'm not sure what the workaround is for localhost, maybe serving those helper files (option 4) on localhost at the same time?

Code-Hex commented 8 months ago

By the way, our environment is option 5. The .web.app domain is already referenced in many places, and it would be difficult to change the domain now.

michealroberts commented 7 months ago

Just to add something here, I am convinced that both onAuthStateChanged and onIdTokenChanged are not firing in some instances, I basically can never get the re-trigger of the token after an hour has elapsed and the token is revoked, even when I call getIdToken(true) with the force refresh trigger...

It feels like at this stage, Firebase auth just needs to be put in a bin and we switch to Clerk or Lucia auth. It's so sad how Google have not looked after this project. :(