坚持使用Firebase的Node.js客户端应用程序用户

时间:2019-04-16 21:06:12

标签: node.js firebase firebase-authentication

我正在使用Firebase构建Node.js命令行界面(CLI) 用于后端身份验证。我想避免让用户在每次运行命令时都键入密码。相反,我想实现一个“登录”流程,该流程将持久保存文件系统的凭据,该凭据可用于后续的无密码身份验证,直到用户“注销”为止。

基本上我要寻找的是firebase JavaScript SDK's“身份验证状态持久性”功能。不幸的是,Node.js不支持该功能。在此模式下使用setPersistence'local'调用'session'会引发错误“当前环境不支持指定的持久性类型。”

“靠我自己”实现该功能的最简单方法是什么?

我研究了SDK如何在浏览器中保留用户,并基本上将用户对象字符串化并将其存储在本地存储中。我可以在Node.js中轻松地自己对用户对象进行字符串化(该实例具有toJSON方法),但是我不知道如何稍后将字符串反序列化为firebase.User的实例。我看到this function in the source code似乎可以解决问题。但这并未在SDK AFAIK上对外公开。

4 个答案:

答案 0 :(得分:1)

您可以从序列化的用户对象实例化firebase.User类:

保存用户

const userJson = JSON.stringify(currentUser.toJSON())
// Write userJson to disk

加载用户

// Read userJson from disk
const userData = JSON.parse(userJson)
const user = new firebase.User(userData, userData.stsTokenManager, userData)
firebase.auth().updateCurrentUser(user)

来源:https://github.com/firebase/firebase-js-sdk/issues/1874#issuecomment-549085119

答案 1 :(得分:0)

In CLI applications that require tokens it is common for these tokens to be stored somewhere on the local machine (often in a "dot" file in the home directory for Linux machines - e.g. ~/.yourapp/config.

These files can be in any format you want but I like JSON or YAML to store things like this.

In terms of the User object you can easily load the string with the Node.js builtin JSON.parse(yourStringUser).

Within the firebase-js-sdk source code you can find references where similar is performed with session storage; using the toJSON() method to set with a certain key and retrieving that value with the JSON.parse() method.

答案 2 :(得分:0)

Session management with service workers

end users will have Node.js installed locally - and your wanting to build an interactive Node script/app which requires client/token access to Firebase.

Firebase Auth provides the ability to use service workers to detect and pass Firebase ID tokens for session management.

If you look at how the Firebase CLI itself works, users log in via a web browser then paste an auth code into the Firebase CLI (firebase login --no localhost). Then, the user is signed in. So, use a browser and the Firebase Web SDK to collect the credentials.

答案 3 :(得分:0)

我在Google Cloud Platform支持下进行了详尽的探讨,我们确定当前的SDK无法实现这一点。 FWIW,此功能仅花了我几个小时即可使用AWS Cognito实施。 the CognitoUser constructor允许用户传递自己喜欢的localStorage API的Node.js实现。