I’m using a sveltekit app for the frontend, and a python backend. I’m using the admin sdk to perform server-side validation and storing the cookies, using that each time I make a request to my backend.
The problem is that although the cookies should remain valid for much longer, it seems to be expiring every hour.
{
"detail": "Invalid authentication. Token expired, 1700799416 < 1700846629"
}
I’ve tried looking through the documentation and it seemed like Firebase handles automatic refreshing of tokens, but clearly I’m misunderstanding something.
I’ve seen similar questions like How to refresh Firebase IdToken after it expires? but there doesn’t seem to be a clear answer on how to fix the problem.
Does anyone know what I’m doing wrong?
Here’s where I’ve implemented getIdToken() client-side
export async function googleAuth() {
const provider = new GoogleAuthProvider();
const credential = await signInWithPopup(auth, provider);
const idToken = await credential.user.getIdToken();
try {
const res = await fetch('/api/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ idToken })
});
if (!res.ok) {
throw new Error('Network response was not ok ' + res.statusText);
}
console.log("User successfully signed in with Google");
return credential;
} catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
console.log("User successfully signed in with Google")
return credential
}
This is where the token auth fails (server side)
export const load = (async ({ locals, params }) => {
const uid = locals.userID;
const idToken = locals.idToken
if (!uid) {
throw redirect(301, "/login")
}
let message_bookmark: string = ''
const formData = new FormData();
formData.append("user_id", uid)
formData.append("message_bookmark", message_bookmark)
const messagesContent = await fetch(
`${import.meta.env.VITE_API_URL}/get-message-history`,
{
method: "POST",
body: formData,
headers: {
'Authorization': `Bearer ${idToken}`
},
}
);
const messagesContentData = await messagesContent.json()
messagesContentData.body.idToken = idToken;
messagesContentData.body.userId = uid;
return messagesContentData
}) satisfies PageServerLoad
2
Answers
The problem was that while I was storing the cookie, I wasn't actually using it to make requests. I was still using the idToken - switching to using the cookie fixed the issue.
ID tokens minted by Firebase Authentication are valid for an hour. There’s no way to expand that time.
What you can do is exchange the ID token for a session cookie, and those can be valid for up to 2 weeks.
Note that both ID tokens and session cookies are so-called bearer tokens, which means they can’t be revoked once minted. If you want to disable the use of a token/cookie, you will have to create your own registry of revoked tokens and check that. For more on this, see the Firebase documentation on managing sessions.