When refreshing the page, client Firebase seems to think I have an authenticated user, but the firestore firebase rules imply that I don't have an authenticated user.
I have a Firebase app where users sign in with email and password via signInWithEmailAndPassword
. I set persistence to browserLocalPersistence
. Normally when a user logs in, the onAuthStateChanged
method is called with the authenticated user object and the application runs normally. When the user refreshes the page, my onAuthStateChanged
method fires again with a non-null user, but all Firebase queries fail due to my security rules. What am I doing wrong there.
This is a reactjs application. Please let me know if I can provide any other answers that might inspire you.
My firebase rules:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if isAuthenticated(); } function isAuthenticated() { return request.auth != null && request.auth.uid != null; } } }
My login code:
setPersistence(sharedFirebaseAuth, browserLocalPersistence) .then(() => { signInWithEmailAndPassword(sharedFirebaseAuth, email, password) .then((userCredential) => { }) .catch((error) => { }); })
My onAuthStateChanged code
onAuthStateChanged(sharedFirebaseAuth, (user) => { if(user){ user.reload().then(()=>{ requestDocs(); }); } })
I think you forgot the comma between
read
andwrite
, it should look likeallow read, write: if isAuthenticated();
I ended up having to implement an authentication provider so that it retained my user information.
New file AuthContext.tsx
New file AuthProvider.tsx
Then I updated my index.tsx like this
Then update the part of app.tsx where I call onAuthStateChanged to the following
After refreshing, it seems to retain all the necessary authentication information to extract the document.