workos / authkit-nextjs

The WorkOS library for Next.js provides convenient helpers for authentication and session management using WorkOS & AuthKit with Next.js.
MIT License
43 stars 9 forks source link

Refresh Token Race Condition #28

Closed wthomsen closed 1 month ago

wthomsen commented 2 months ago

Thanks for this library!

Is there a recommended approach to handle race conditions on rotating refresh tokens? In my case an API is sending parallel requests so during a session refresh only the first request succeeds. I know some auth backends allow a short grace period on refresh tokens before sending the "already exchanged" error. Any easy solution or do I have to roll my own gate?

PaulAsjes commented 2 months ago

Hey there! Can you explain your set up a little bit more so we can understand why you're getting a race condition when using the refresh token?

wthomsen commented 2 months ago

Sure. Right now I'm hitting issues in local development where a stale tRPC query conflicts with a Fast Refresh. On prod the race condition occurs with any sort of concurrency. For example, a page might revalidate data on tab re-focus and simultaneously hit three API endpoints.

PaulAsjes commented 2 months ago

Confirming I've seen this happen in development. I think it's due to how Fast Refresh works when working with Next's dev server.

I'm going to look further into this, but the simple solution might just be for us to add debouncing to the refresh token auth call.

pawel-alphadoc commented 2 months ago

We are also having this issue. Usually it's happening during development (after adding some changes), but unfortunately it's also happening sometimes on a production. I'm adding logs that we are getting

image (2)

brandfocus commented 1 month ago

Also running into this issue. Has anyone found a workaround?

PaulAsjes commented 1 month ago

Thanks for your patience, all. We shipped an update to the WorkOS API that adds a grace period for authenticating with refresh tokens. Now if more than one call is made in a short amount of time, the same new refresh token will be returned.

I'm going to close this issue as this should fix the problem, however please feel free to reopen if you're still seeing issues.