【问题标题】:How to verify email/password credentials using Firebase Admin SDK (server-side)?如何使用 Firebase Admin SDK(服务器端)验证电子邮件/密码凭据?
【发布时间】:2023-04-09 17:16:01
【问题描述】:

我在本地 Mac 上编写了一个 Google Cloud Function Express 应用和一个使用 Node.js 的命令行工具。

致电myclitool login,会出现一次性提示,要求用户提供电子邮件和密码。 CLI 工具使用 HTTP POST 请求通过 SSL 将请求正文中的电子邮件和密码发送到 Express 服务器。

服务器将发回一个私有 API 密钥(由用户注册时的触发函数生成),该密钥将写入~/.myclitoolrc,并将用于对我的 API 端点的所有后续调用。

来自 CLI 工具的每个后续调用都将在 Firestore 帐户集合中查找私有 API 密钥,并基于每个 API 调用进行身份验证。

admin.firestore()
  .collection('accounts')
  .where('privateApiKey', '==', privateApiKey)
  .get() // and so on

到目前为止,以下代码将定位到admin.auth.UserRecord

Service.prototype.signin = function signin(email, password) {
  return new Promise(function(resolve, reject) {
    admin.auth().getUserByEmail(email)
    .then(userRecord => {
      console.log(userRecord);
      resolve('some value later');
    })
    .catch(err => {
      reject(err);
    });
  });
};

Firebase 文档说: https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord

passwordHash(字符串或空)

用户的哈希密码(base64 编码),仅当 Firebase Auth 使用散列算法(SCRYPT)。如果使用不同的哈希算法 已在上传此用户时使用过,这在迁移时很常见 从另一个 Auth 系统,这将是一个空字符串。如果没有密码 已设置,这将为空。这仅在用户处于 从 listUsers() 获取。

passwordSalt(字符串或空)

用户的密码 salt(base64 编码),仅当 Firebase Auth 使用散列算法(SCRYPT)。如果使用不同的哈希算法 已用于上传此用户,通常在从另一个用户迁移时 验证系统,这将是一个空字符串。如果没有设置密码,这个 将为空。这仅在从以下位置获取用户时可用 列表用户()。

检索到的 UserRecord 包含 SCRYPTd passwordHashpasswordSalt 属性。

UserRecord {
  uid: 'kjep.[snip]..i2',
  email: 'email@example.com',
  emailVerified: false,
  displayName: undefined,
  photoURL: undefined,
  phoneNumber: undefined,
  disabled: false,
  metadata: 
   UserMetadata {
     creationTime: 'Thu, 12 Apr 2018 09:15:23 GMT',
     lastSignInTime: 'Thu, 03 May 2018 03:57:06 GMT' },
  providerData: 
   [ UserInfo {
       uid: 'email@example.com',
       displayName: undefined,
       email: 'email@example.com',
       photoURL: undefined,
       providerId: 'password',
       phoneNumber: undefined } ],
  passwordHash: 'U..base64..Q=',
  passwordSalt: undefined,
  customClaims: undefined,
  tokensValidAfterTime: 'Thu, 12 Apr 2018 09:15:23 GMT' }

Firebase Admin SDK admin.auth() 中似乎没有验证功能。

我应该通过寻找算法或现成的 Node 模块自己实现 SCRYPT 验证,还是应该将没有任何验证功能视为这不是最佳方法的标志?

如果是这样,请推荐一个更好的设计,记住这是一个原型项目,实现完整的 Oauth2 将非常耗时。

【问题讨论】:

  • 如果您只是想允许从 Node 应用程序对 Cloud Firestore 的受控访问,您可以使用标准 Firebase Javascript SDK 并强制执行安全规则。让我知道这是否是您的用例,我将发布一些代码示例。
  • 我想通过 RESTful 端点公开我的服务,因此使用 Firebase JavaScript SDK 可能不适合 CLI 工具提供的所有命令类型。很高兴看到任何示例以获得更多想法。

标签: firebase firebase-authentication google-cloud-firestore google-cloud-functions firebase-admin


【解决方案1】:

根据 cmets 的要求,这里是一些示例代码,用于通过 Firebase Javascript SDK 使用 Node.js 访问 Cloud Firestore(执行安全规则)。

在 v4.13.0(现已关闭)中提交了一个错误。我还没有测试 4.13.1,但修复已合并到 master 分支中。如果还是不行,你应该试试 v4.12.0。

const firebase = require('firebase');
require("firebase/firestore");

// Initialize Firebase
// You get these details from the Firebase Console
let config = {
  apiKey: "yourAPIkey",
  authDomain: "yourAuthDomain",
  databaseURL: "https://yourProjectID.firebaseio.com",
  projectId: "yourProjectID",
  messagingSenderId: "yourId"
};
firebase.initializeApp(config);

let email = 'yourUser@example.com';
let password = 'yourVerySecurePassword';

firebase.auth().signInWithEmailAndPassword(email, password)
  .catch(error => {
    console.log(error);
  });

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    console.log('I am logged in');

    // Initialise Firestore
    const firestore = firebase.firestore();
    const settings = {timestampsInSnapshots: true};
    firestore.settings(settings);

    return firestore
      .collection('accounts')
      .where('privateApiKey', '==', privateApiKey)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((documentSnapshot) => {
          if (documentSnapshot.exists) {
            console.log(documentSnapshot.id);
          }
        });
      });
  } else {
    // User is signed out.
    // ...
  }
});

【讨论】:

  • 这会记录你,这可能是一个意外的副作用。
猜你喜欢
  • 2018-01-01
  • 2021-04-18
  • 2021-07-09
  • 2023-03-24
  • 2021-11-21
  • 1970-01-01
  • 2020-10-19
  • 2017-11-16
  • 2020-02-16
相关资源
最近更新 更多