简体   繁体   English

带有 Express 后端的 Firebase 身份验证和实时数据库

[英]Firebase Auth and Realtime Database with Express Backend

I'm currently working on a project that expands on an existing web application that is using Firebase Auth and Realtime Database, both of which are used directly by the client.我目前正在开发一个项目,该项目扩展了使用 Firebase 身份验证和实时数据库的现有 Web 应用程序,这两者都由客户端直接使用。 I want to expand my website to have server side rendering, so I'm planning on changing my website from being hosted on GitHub Pages to Heroku using Express.我想扩展我的网站以进行服务器端渲染,因此我计划将我的网站从托管在 GitHub Pages 上更改为使用 Express 的 Heroku。

The issue I'm currently having is how to get the authenticated user when navigating between pages, as I want to pre-render pages depending on the authenticated user.我目前遇到的问题是如何在页面之间导航时获取经过身份验证的用户,因为我想根据经过身份验证的用户预呈现页面。 The auth API has the firebase.auth().currentUser.getIdToken() function, but this requires running JavaScript on the client before sending a request to the server. auth API 具有firebase.auth().currentUser.getIdToken()函数,但这需要在向服务器发送请求之前在客户端上运行 JavaScript。 Is there a way to store this token in a cookie or session that is automatically sent to the server when making requests?有没有办法将此令牌存储在发出请求时自动发送到服务器的 cookie 或会话中?

One solution I've come up with is to remove all Firebase libraries from the client and make all these auth and database actions through the server, but I'm worried that this will worsen the usr experience and it would take more time between actions, as there is no local copy of the database for on value change listeners.我提出的一种解决方案是从客户端删除所有 Firebase 库,并通过服务器进行所有这些身份验证和数据库操作,但我担心这会恶化 usr 体验,并且操作之间会花费更多时间,因为没有用于值更改侦听器的数据库的本地副本。

You can use the Firebase admin api.您可以使用 Firebase管理API。 It lets you manage the server side session cookie.它允许您管理服务器端会话 cookie。 The way I see on how you can solve the problem is by means of session cookies.我认为如何解决问题的方式是通过会话 cookie。 You need to implement a session login then verify the session cookie.您需要实现会话登录,然后验证会话 cookie。 Lastly, generate the content based on the data from the cookie.最后,根据 cookie 中的数据生成内容。

Example taken from docs :取自文档的示例:

 // Whenever a user is accessing restricted content that requires authentication. app.post('/profile', (req, res) => { const sessionCookie = req.cookies.session || ''; // Verify the session cookie. In this case an additional check is added to detect // if the user's Firebase session was revoked, user deleted/disabled, etc. admin.auth().verifySessionCookie( sessionCookie, true /** checkRevoked */) .then((decodedClaims) => { serveContentForUser('/profile', req, res, decodedClaims); }) .catch(error => { // Session cookie is unavailable or invalid. Force user to login. res.redirect('/login'); }); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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