简体   繁体   中英

How to set the `currentUser` in Firebase when using sessions/cookies for persistence?

I'm using sessions/cookies to authenticate my Firebase users.

The persistence on the client is set to "none" ( auth.setPersistence(inMemoryPersistence) ) and I'm using admin.auth().verifySessionCookie() on the server to validate each request.

The issue is that on the client/browser, auth.currentUser is always null .

Normally I wouldn't care about auth.currentUser , because I'm sending all the user info I need from the server to the client anyway. But if I want to use @firebase/storage , then the user needs to be authenticated locally on the client in order to be able to upload files and match the security rules.

What mechanism should I use to be able to set the currentUser on the client?

auth.currentUser is always null

That will be null as you are not logged in with the Firebase SDK itself. As mentioned in the documentation , they are meant for traditional websites that use session cookies. You are not logged in with the Firebase SDK itself.

What mechanism should I use to be able to set the currentUser on the client?

You can add an API endpoint in your server (eg GET /auth/user ) that'll return user information if the cookies is present else null and redirect user to login page.

But if I want to use @firebase/storage , then the user needs to be authenticated locally on the client in order to be able to upload files and match the security rules.

Don't set the persistence to NONE . That way you'll still be logged in with the client SDK and your requests will still be authenticated (unless you want to use the REST API and handle it yourself).

However, it's not the best way to use both the methods as using signOut() from the SDK won't discard the session cookie and you must handle that explicitly. You can also route your Firebase Storage requests through the server depending on the use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM