Reputation: 301
To increase the performance of my react app on page reload, I store user credentials on local storage and clear them on logout. But users often not logout these days and user credentials can stay in local storage for long time which I think can lead to some security leaks? I am no expert on firebase security so can someone explain if is it safe?
firebase.auth().onAuthStateChanged(user=>{
if (user) {
localStorage.setItem('user', JSON.stringify(user));
} else {
localStorage.removeItem('user');
}
})
Upvotes: 5
Views: 4626
Reputation: 7100
I would suggest to change the persistent to Persistent.SESSION
.
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
Yes, this do not cover the whole problem (because user also may not close the browser) but it makes a sense.
Upvotes: 0
Reputation: 599041
On most platforms the Firebase Authentication SDK already automatically stores the user's credentials in local storage, and reloads it from there when the app restarts/page reloads. The reason you still see a delay on a page reload before onAuthStateChanged
fires, is because the client checks with the server to see if the credentials are (still) valid.
A simple workaround to be able to act right away when the page loads, while Firebase is checking the credentials, is to store a value about the last known authentication state in local storage yourself and use that to determine your initial action. That's essentially what you're doing with the user
object in your question.
There is nothing wrong with that, as long as you understand that the first time onAuthStateChanged
fires, the data may be different from what you stored. It typically won't be, but it may, which is the whole reason Firebase has to check the credentials to begin with.
Also see my answer to this related question from yesterday: Firebase auth.currentUser is null when loading the page, user loaded when authstatechange called after some milli seconds of page load
Upvotes: 4