首页 文章

如何在没有客户端身份验证的情况下从服务器验证firebase用户?

提问于
浏览
3

我有一个API,它使用节点admin sdk连接并调用firebase . 我的客户为他们需要的所有东西打了我的api . 我不希望他们必须直接调用firebase进行身份验证,因为我希望客户端代码与api和后端分离 .

服务器如何验证它们?基于当前的文档,即使至少客户端必须向api提供他们的uid(假设他们自己进行身份验证,对吧?) .

理想情况下,客户端会通过ssl向我的api提供POST的正文中的用户名和密码,并且api会将其登录并发送回他们的id令牌 . 建议的方法是什么?

2 回答

  • 3

    如果要使用Firebase进行身份验证,最好通过客户端SDK在客户端进行处理 . 这是因为身份验证是基于IP地址的速率限制的,它还允许您跳过会话管理和持久性中的编码过程 .

    但是,如果您希望通过在服务器上托管客户端SDK并将请求移交给Firebase,您可以实现所需的登录/用户数量 .

    // app.js
    
    const bodyParser = require('body-parser');
    const cookieParser = require('cookie-parser');
    const express = require('express');
    const firebase = require('firebase'); // client SDK
    
    firebase.initializeApp({
      apiKey: "<API_KEY>",
      authDomain: "<PROJECT_ID>.firebaseapp.com"
    });
    
    const app = express();
    app.use(bodyParser.json());
    app.use(cookieParser(['array', 'of', 'secrets']));
    
    // on future requests, the UID can be found using `req.cookies['__session'].uid`
    
    app.post('/login', function (req, res, next) {
      if (!req.body.email) return res.status(400).json({error: 'missing email'});
      if (!req.body.password) return res.status(400).json({error: 'missing password'});
    
      firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE) // don't persist auth session
      .then(function() {
        return firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password)
      });
      .then((user) => { // https://firebase.google.com/docs/reference/js/firebase.User
        let uid = user.uid;
    
        // set cookie with UID or some other form of persistence
        // such as the Authorization header
        res.cookie('__session', { uid: uid }, { signed: true, maxAge: 3600 });
        res.set('cache-control', 'max-age=0, private') // may not be needed. Good to have if behind a CDN.
        res.send('You have successfully logged in');
    
        return firebase.auth().signOut(); //clears session from memory
      })
      .catch((err) => {
        next(err);
      });
    });
    
    module.exports = app;
    

    Note: 您也可以考虑使用Cloud Functions共同查找您的API . 根据您的使用情况,这可能是具有成本效益的选择 .

  • 5

    只是想提供一个更新:有关未记录的REST API的答案可以在这里找到:Firebase REST auth when creating token with node.js admin sdk

    如果可以,我会将此标记为答案 .

相关问题