-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Description
Environment
When rotating tokens, new token is not stored and thus not reused, so token is lost. The old token still persists instead and used for all further iterations of current session.
Only initial token generated on login works and reused constantly.
I use Keycloak as the external IDP
Keycloak — 21.1.1
Nextjs — 13.4.2
Next-auth — 4.22.1
Node — 16.2.0, 19.9.0
Reproduction URL
https://github.com/mrbodich/next-auth-example-fork.git
Describe the issue
When I use async jwt()
function in callbacks
section, I get the new token from external IDP successfully, create the new token object and return in async jwt()
just like documentation says.
Here is my piece of code in the last else
block (if access token is expired)
} else {
// If the access token has expired, try to refresh it
console.log(`Old token expired: ${token.expires_at}`)
const newToken = await refreshAccessToken(token)
console.log(`New token acquired: ${newToken.expires_at}`)
return newToken
}
Once token expired, and else
block is executed, I have constantly updating at each request. Here is what I get in the console logged:
Old token expired: 1684147058
Token was refreshed. New token expires in 60 sec at 1684147125, refresh token expires in 2592000 sec
New token acquired: 1684147125
Old token expired: 1684147058
Token was refreshed. New token expires in 60 sec at 1684147128, refresh token expires in 2592000 sec
New token acquired: 1684147128
Old token expired: 1684147058
Token was refreshed. New token expires in 60 sec at 1684147132, refresh token expires in 2592000 sec
New token acquired: 1684147132
As you see, 1684147058
is not changed between requests, so new JWT is just lost somewhere and not used for later requests. Though at the first login, returned jwt is used correctly.
How to reproduce
- Clone this repo https://github.com/mrbodich/next-auth-example-fork.git
- Transfer
.env.local.example
file to.env.local file
- When signing in, use credentials from
.env.local.example
file,row 13
- After sign-in, token will start refreshing after 1 minute (token lifespan set in Keycloak)
- Look in the console for next-auth logs
18 ... 25
in the index.tsx
file (getServerSideProps function), and tokens will start rotating fine.
Expected behavior
Token returned in the async jwt()
function in callbacks
section must be used on the next request and not being lost.