awinogrodzki / next-firebase-auth-edge

Next.js Firebase Authentication for Edge and Node.js runtimes. Compatible with latest Next.js features.
https://next-firebase-auth-edge-docs.vercel.app/
MIT License
506 stars 44 forks source link

How to revalidate id token #264

Open fedetoledo opened 1 week ago

fedetoledo commented 1 week ago

After 1 hour the id token expires, and the user is not logged out. How can I revalidate the id token. Is it something I can do with the library or with plain firebase SDK.

Would like some help here.

Right now I'm getting the id token like this from my layout page:

const tokens = await getTokens(cookies(), {
    ...authConfig,
    headers: headers(),
  });

I assume I have to validate the token after getting it, and if it's not valid get the new one, but not sure how to make it work.

Something weird are the iat and exp times, which are dates from 1970 (epoch):

iat: 1728606399,
exp: 1728609999
awinogrodzki commented 1 week ago

Hey @fedetoledo,

Middleware automatically handles token revalidation. The timestamps you've provided are correct.

iat: 1728606399,
exp: 1728609999

Both iat and exp are values in seconds, whereas JavaScript Date object requires miliseconds.

If you debug those dates like this:

new Date(1728606399 * 1000)

You can see the correct date. In my case it's:

Fri Oct 11 2024 02:26:39 GMT+0200 (Central European Summer Time)
fedetoledo commented 1 week ago

@awinogrodzki I should have posted the error I'm getting. If the middleware revalidates the token automatically, there's another issue, maybe the client side is not refreshing?

Failed to fetch data Error 401: Firebase ID token has expired. Get a fresh ID token from your client app and try again (auth/id-token-expired). See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
 ⨯ Error: Failed to fetch data: Error 401: Firebase ID token has expired. Get a fresh ID token from your client app and try again (auth/id-token-expired). See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
awinogrodzki commented 1 week ago

Hey @fedetoledo,

Where is that error coming from? Do you have some stack trace? Is it client or backend side?