firebase / firebase/firebase-js-sdk

ID token refresh fails when using Persistence.Cookie auth persistence method

Open
#9,018 5 comments 1 reaction 1 assignee Claimed by @jamesdaniels View on GitHub
api: auth bug needs-attention Repro Needed stack:NextJS
Dominant language
TypeScript
Stars
5.1k
Forks
1k
Avg merge
2d 21h
Merged PRs (30d)
37

Description

### Operating System

MacOS Sequoia Version 15.1.1

### Environment (if applicable)

All browsers

### Firebase SDK Version

11.6.1

### Firebase SDK Product(s)

Auth

### Project Tooling

React app with Next.js

### Detailed Problem Description

Saw that there was a new [Persistence.Cookie strategy](https://firebase.google.com/support/release-notes/js#authentication_1) for Auth in beta and decided to give it a try, since it should fix some Auth persistence issues we have in Safari. I'm mostly following the implementation from [this PR](https://github.com/FirebaseExtended/reactfire/pull/640/files).

It works great, except if a user logs in and doesn't close their browser for an hour, and the ID token expires, Firebase fails to refresh it. This logs the user out. Other persistence strategies don't seem to have this issue. I'm seeing that the error code is `user-token-expired`.

This seems to be because:
1. When `PersistenceUserManager.getCurrentUser` is called, the user [is created using the stored cookie value](https://github.com/firebase/firebase-js-sdk/blob/39505cc72d346ed8fa75267181fd80fb046f5635/packages/auth/src/core/persistence/persistence_user_manager.ts#L76). This user has `refreshToken = null` since the cookie value is just a string with the ID token and does not have the refresh token.
2. When the ID token is about to expire or expired and `getIdToken` refreshed, [this line fails](https://github.com/firebase/firebase-js-sdk/blob/39505cc72d346ed8fa75267181fd80fb046f5635/packages/auth/src/core/user/token_manager.ts#L90) since the refresh token is `null`.

### Steps and code to reproduce issue

1. Set auth persistence to `browserCookiePersistence`:
```
auth.setPersistence(browserCookiePersistence);
```
2. Set up Next.JS middleware to handle browser cookie persistence ([example](https://github.com/FirebaseExtended/reactfire/pull/640/files))
3. Without closing the browser tab/window, wait an hour so that the ID token expires (or lower the refresh interval so that the force refresh happens more quickly)

**Expected result:**
User remains logged in, and ID token is refreshed. Firebase makes a request to `/__cookies__` endpoint to refresh the ID token.

**Actual behavior**
The ID token expires and is not refreshed. The error code received is `user-token-expired`. A `DELETE` request is sent to `/__cookies__` endpoint to log the user out.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.