firebase - 使用 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)发送到服务器以“注册”此令牌?
最后一部分是(所有)教程似乎遗漏的部分。
解决方案
推荐阅读
- python - 如何在 Python 中从 matplotlib 行生成坐标列表
- python - 从多索引表中获取最大行
- python - 在循环中创建多个密度图
- nginx - 将反向代理设置从 apache 转换为 Nginx
- c# - WPF XAML C# - XAML 中定义的文本框为空
- javascript - 我怎样才能得到调用者的`this`?
- javascript - 如何解决在我的 React App 中检查 Header 的渲染方法?
- python - 如何在 TDS 游戏 pygame 中在碰撞时删除精灵
- ios - 为什么我的 tableview 出口为零?
- typescript - 在键是字符串且值是 Typescript 中的对象数组的对象中声明类型的正确方法是什么?