-
Notifications
You must be signed in to change notification settings - Fork 408
How to automatically refresh expired id token using Firebase Admin SDK #2471
-
I have a SvelteKit app which uses Firebase Authentication. The auth flow is like this
- when user clicks log in, I will call the below function on the client
export async function loginWithGooglePopup() {
const credential = await signInWithPopup(auth, authProvider);
const idToken = await credential.user.getIdToken();
if (idToken) {
// call my own SvelteKit api route
await fetch('/api/login', { method: 'POST', body: JSON.stringify({ idToken }) });
await invalidateAll();
}
}
- then in my
/api/login/+server.tsI will verify the id token given above and set my own SvelteKit cookie
export const POST: RequestHandler = async ({ request, cookies }) => {
const { idToken } = await request.json();
const expiresIn = 60 * 60 * 24 * 5 * 1000; // 5 days
try {
const decodedToken = await adminAuth.verifyIdToken(idToken);
const cookie = await adminAuth.createSessionCookie(idToken, { expiresIn });
const options = {
maxAge: expiresIn,
httpOnly: true,
secure: PUBLIC_ENVIRONMENT === 'production' ? true : false,
path: '/'
};
// use decodedToken to insert user data into database and do other stuff
cookies.set('__session', cookie, options);
return json({ status: 200 });
} catch (err) {
error(401,);
}
};
The reason I don't use onAuthStateChanged is it only works on the client and will make a flash between logged-out and logged-in user
- Then in my
+hooks.server.ts(a middleware file in SvelteKit) I will verify the id token on every request like this
import { adminAuth } from '$lib/server/firebase-admin/config';
export const handle: Handle = async ({ event, resolve }) => {
const sessionCookie = event.cookies.get('__session');
if (!sessionCookie) return await resolve(event);
try {
const userCookie = await adminAuth.verifySessionCookie(sessionCookie);
event.locals.user = { ...userCookie }
} catch (e) {
console.log(e)
}
return await resolve(event);
};
The problem I'm having is when verifySessionCookie throws an error of auth/session-cookie-expired I couldn't find any method to request a new id token on the server. In addition, I don't want to redirect the user to the login page which is annoying. How do I achieve this?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments
-
add onIdTokenChanged event handler using auth instance the call this api route
auth.onIdTokenChanged( async(user)=> {
await fetch('/api/login', { method: 'POST', body: JSON.stringify({ idToken:await user.getIdToken() }) });
})
this will get triggered once the id token in the client expired and firebase explicitly creates a new one then make your fetch with the new idToken to always hava updated token
Beta Was this translation helpful? Give feedback.
All reactions
-
This issue is probably related to your question, but no answer yet
Beta Was this translation helpful? Give feedback.