[英]Firebase: How do I get the ID Token for a signed-in user on the client side if I am using server-side session cookies?
I am using Firebase Cloud Functions with Express and Firebase Hosting to serve my multi-page site.我正在使用带有 Express 和 Firebase 托管的 Firebase 云功能来为我的多页站点提供服务。 I have successfully implemented server-side cookies as explained here and as implemented below:我已经成功实现了服务器端 cookies,如此处所述,并如下实现:
function verifyLogin(request, response, next) {
const sessionCookie = request.cookies.__session || '';
firebase.auth().verifySessionCookie(sessionCookie, true /** checkRevoked */ )
.then((decodedClaims) => {
//serve content for user
return next();
}).catch(error => {
// Session cookie is unavailable or invalid. Force user to log in.
console.log(error);
response.redirect('/login');
return;
});
}
app.get('/', verifyLogin, (request, response) => {
var page_title = "Home";
response.render('index', {
page_title,
});
});
I am using the Firebase Web SDK (JavaScript) to access the Firebase Cloud Firestore.我正在使用 Firebase Web SDK (JavaScript) 访问 Z035489FF8D092741943E4 Cloud Firestore。 In order to do this, I need to get the idToken on the client side for the currently-logged-in user, like so:为此,我需要在客户端获取当前登录用户的 idToken,如下所示:
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
firebase.auth().currentUser.getIdTokenResult()
.then((idTokenResult) => {
// Access the Firebase Cloud Firestore here
});
}
});
This seems redundant to me, since I already know which user is signed in via my server cookie, but how else can I get the idToken without another call to Firebase Auth?这对我来说似乎是多余的,因为我已经知道哪个用户是通过我的服务器 cookie 登录的,但是如果不再次调用 Firebase Auth,我还能如何获得 idToken?
Is there a way to extrapolate it from my session cookie somehow and pass it to my client from my cloud function as a variable?有没有办法以某种方式从我的 session cookie 中推断出来,并将其从我的云 function 作为变量传递给我的客户端?
Or is there another way to look at this philosophically that I am overlooking?还是有另一种我忽略的哲学方式来看待这个问题?
In the same way you can listen to user sign-in state changes using onAuthStateChanged()
, you can also listen to user ID token changes using onIdTokenChanged() .同样,您可以使用onAuthStateChanged()
监听用户登录 state 更改,也可以使用onIdTokenChanged () 监听用户 ID 令牌更改。 You will only need to use a new token when the observer you attach shows that a new one appears (for example, when it's refreshed every hour by the SDK).仅当您附加的观察者显示出现新令牌时(例如,当 SDK 每小时刷新一次时),您才需要使用新令牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.