首页 > 解决方案 > 使用 Firebase 云功能从客户端 Google 登录获取 Bearer 令牌

问题描述

语境:

因此,我想使用 Google 登录功能来允许用户登录(使用我自己的基于电子邮件的中间件验证 - 此处超出范围)。

做一些研究:要启用 Google 登录和客户端网络浏览器,可以在此处找到如何设置它的一个很好的示例。

客户端设置

设置的 TL;DR:

var firebaseConfig = {
    apiKey: //...,
    authDomain: //...,
    databaseURL: //...,
    projectId: //...,
    ...
};

// using the popup/redirect methods, this is necessary to detect changes
firebase.auth().onAuthStateChanged(user => {
    if (user) {
            // authenticated, get user record or access token (see documentation)
        } else {
            // not authenticated - perform action
        }
    }
});

// using the loginWithGoogle event, try logging in
loginWithGoogle.addEventListener('click', e => {
    var provider = new firebase.auth.GoogleAuthProvider();
    firebase.auth()
        .signInWithPopup(provider) // or signInWithRedirect(provider) - this will redirect and you must use the onAuthStateChanged else you will be logged in and remain on the e.g. login window
        .then(value => {
            // we are logged in using the popup
            console.log(value);
        })
        .catch((error) => {
            var errorMessage = error.message;
            alert(errorMessage);
    });
})

云功能/服务器端设置:

在您的快速应用程序设置中的某个地方,您希望有一个中间件功能来检查req.headers.authorization标头中的不记名令牌并对其进行验证,请参阅以获取更多信息。

它看起来像这样:

if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
    !(req.cookies && req.cookies.__session)) {
    functions.logger.error(
        'No Firebase ID token was passed as a Bearer token in the Authorization header.',
        'Make sure you authorize your request by providing the following HTTP header:',
        'Authorization: Bearer <Firebase ID Token>',
        'or by passing a "__session" cookie.'
    );
    res.status(403).send('Unauthorized');
    return;
}

问题:

我找不到与使用此方法(也不是在示例中)进行注册有关的任何进一步的参考/文档与客户端相关的任何内容。

您现在可能已经意识到我遗漏了一些重要的东西 - 我在哪里获取/使用/存储/保存Bearer token以访问下一个(需要身份验证)页面。

问题:

重定向(成功登录后)到需要身份验证的页面时,req.headers.authorization报告为undefined,因此我“显然”未经身份验证。

在使用我可以访问idToken等的 Google 登录进行身份验证后,我是否需要将此(使用例如 AJAX)发送到服务器以“注册”此令牌?

最后一部分是(所有)教程似乎遗漏的部分。

标签: firebasegoogle-cloud-platformfirebase-authenticationgoogle-signingoogle-api-nodejs-client

解决方案


推荐阅读