Help with refresh tokens
Unanswered
Hairy Woodpecker posted this in #help-forum
Hairy WoodpeckerOP
Hello, there is a problem with the fact that /api/auth/session from next-auth is called twice in a row when the page loads
Because of this, the refresh Access Token behaves incorrectly and when I resend it, I get an error that this token has already been reset. How do I remove the repeated call to /api/auth/session when loading a page? The code used is shown below.
"next": "14.2.2",
"next-auth": "^4.24.7",
Thanks!
GET /api/auth/session 200 in 20 ms
GET /api/auth/session 200 in 14 msBecause of this, the refresh Access Token behaves incorrectly and when I resend it, I get an error that this token has already been reset. How do I remove the repeated call to /api/auth/session when loading a page? The code used is shown below.
"next": "14.2.2",
"next-auth": "^4.24.7",
Thanks!
2 Replies
Hairy WoodpeckerOP
async function refreshAccessToken(token: any) {
try {
const data = {
staffId: token.staffId,
refreshToken: token.refreshToken
}
const res = await axios.post('/api/v1/admin/staff/refresh_token', data);
const refreshedTokens = await res.data;
token.accessToken = refreshedTokens.result.accessToken
token.accessTokenExpires = Date.now() + 900 * 1000
token.refreshToken = refreshedTokens.result.refreshtoken
console.log(token)
return token
} catch (e) {
console.log("Error")
console.log(e)
return {
error: "RefreshAccessTokenError",
}
}
}
export const authOptions: any = {
providers: [
CredentialsProvider({
id: 'credentials',
name: "Credentials",
credentials: {
email: { label: "Name", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials: any) {
try {
...
} catch (error: any) {
throw new Error(error);
}
}
})
],
callbacks: {
async jwt({ token, user, account, profile, isNewUser }: any) {
if (user) {
token.accessToken = user.result.accessToken
token.accessTokenExpires = Date.now() + 900 * 1000
token.refreshToken = user.result.refreshToken
token.staffId = user.staffId
}
if (Date.now() < token.accessTokenExpires) {
return token
}
return refreshAccessToken(token)
},
}
}Hairy WoodpeckerOP
Bump