如何在服务器上获取 FireBase idToken

How to get a FireBase idToken on the server

根据文档,要验证用户角色,需要检查当前用户的idToken。但是从哪里得到它呢?我刚在客户端找到收据

我试过这样做:

app.get("/admin-cp", function (req, res) {
    const sessionCookie = req.cookies.session || "";
    
    admin
        .auth()
        .verifySessionCookie(sessionCookie, true  )
        .then((userData) => {
            console.log("Logged in:", userData.email)
            console.log('Авторизован. Доступ в админ панель открыт')

            const customToken = admin.auth().createCustomToken(userData.uid)
            admin
            .auth()
            .verifyIdToken(customToken)
            .then((claims) => 
            {  
                if (claims.admin === true) 
                {    
                    // Allow access to admin resource.   
                } 
            });

            res.sendFile(path.join(initial_path, "admin-cp/main-admin_cp.html"));
        })
        .catch((error) => {
            console.log('Не авторизован. Ошибка', error, ' отсутвует userData')
            res.redirect("/login");
        });
});
code: 'auth/argument-error',
message: 'First argument to verifyIdToken() must be a Firebase ID token string.'

您最好在 API 请求的 headers 中从客户端传递 ID 令牌。

const idToken = await firebase.auth().currentUser.getIdToken()

const res = await fetch('/api-url', { headers: { authorization: idToken } })

然后你可以在服务器端读取令牌:

const idToken = req.headers.authorization;

if (!idToken) return res.status(401).send("Unauthorized")

// verify token using verifySessionCookie() here