首页 文章

如何使用Firebase Admin SDK(服务器端)验证电子邮件/密码凭据?

提问于
浏览
1

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

拨打 myclitool login ,一次性提示会询问用户他们的电子邮件和密码 . CLI工具通过SSL使用HTTP POST请求向Express服务器发送请求正文中的电子邮件和密码 .

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

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(string或null)用户的散列密码(base64编码),仅在使用Firebase Auth散列算法(SCRYPT)时 . 如果在上传此用户时使用了不同的哈希算法,这是从其他Auth系统迁移时的典型情况,这将是一个空字符串 . 如果未设置密码,则为空 . 这仅在从listUsers()获取用户时可用 . passwordSalt(string或null)用户的密码salt(base64编码),仅在使用Firebase Auth哈希算法(SCRYPT)时 . 如果使用了不同的哈希算法来上传此用户,则通常从其他Auth系统迁移时,这将是一个空字符串 . 如果未设置密码,则为空 . 这仅在从listUsers()获取用户时可用 .

检索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将是非常耗时的 .

1 回答

  • 0

    根据评论中的要求,以下是一些使用Node.js通过Firebase Javascript SDK访问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.
        // ...
      }
    });
    

相关问题