且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用NodeJS进行Firebase身份验证

更新时间:2022-06-17 07:05:26


Firebase身份验证主要在前端完成

Firebase authentication is mostly done in the front end

正确。当使用Firebase提供的SDK时,用户身份验证完全在客户端完成。

Correct. User auth is entirely done client-side when using the provided SDKs from Firebase.

但是,如果您需要进行一些特殊的身份验证,例如与LDAP / AD集成或其他一些企业恶作剧,那么你需要做自定义令牌创建客户端-s SDK将用于验证用户。

However, if you need to do some special auth, such as integrating with LDAP/AD or some other enterprise shenanigans, then you would need to do custom token creation that client-side SDKs would use to authenticate the user.


我如何获得 req.user 在后端使用Firebase吗?

How can I get req.user to work with Firebase in the back end?

需要自己实施。流客户端将类似于:

This is something you will need to implement yourself. The flow client-side would go something like:


  1. 用户执行auth客户端。

  1. User performs auth client-side.

假设您在请求标头上附加了令牌: FIREBASE_AUTH_TOKEN:abc 。请参阅 Firebase检索用户数据存储在本地存储中作为firebase:authUser:

Let's assume you attach the token on the request header: FIREBASE_AUTH_TOKEN: abc. See Firebase retrieve the user data stored in local storage as firebase:authUser:

所以在服务器端,使用 Firebase Admin SDK ,您将检索该令牌并通过 verifyIdToken 。中间件下面的快速脏示例:

So on the server side, using the Firebase Admin SDK, you will retrieve that token and verify it via verifyIdToken. Quick dirty example below of middleware:

const {auth} = require('firebase-admin');
const authService = auth();

exports.requiresAuth = async (req, res, next) => {
    const idToken = req.header('FIREBASE_AUTH_TOKEN');

    // https://firebase.google.com/docs/reference/admin/node/admin.auth.DecodedIdToken
    let decodedIdToken;

    try {
        decodedIdToken = await authService.verifyIdToken(idToken);
    } catch (error) {
        next(error);
        return;
    }

    req.user = decodedIdToken;
    next();
}

然后你会像这样使用这个中间件:

You would then use this middleware like so:

const express = require('express');
const router = express.Router();
const {requiresLogin} = require('./my-middleware.js');

router.get('/example', requiresLogin, async (req, res) => {
    console.log(req.user)
})

我希望这可以让你知道该怎么做。我暂时没有使用Firebase,上面的信息是我从文档中收集到的信息。

I hope this gives you an idea of what to do. I haven't worked with Firebase for a while and the information above is what I gathered from looking at the documentation.