Reputation: 1
I am creating a web application that allows users to login using their Spotify accounts. The authorization is being handled by auht.js also known as next-auth, but the problem arises when my initial access token expires, and I am trying to refresh it
tried handling the refresh token by first checking if it has expired, if not then send a post request to the Spotify token endpoint and refresh it.
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
Spotify({
authorization:
"https://accounts.spotify.com/authorize?scope=user-read-private user-read-email user-top-read playlist-read-private playlist-read-collaborative",
clientId: process.env.AUTH_SPOTIFY_ID,
clientSecret: process.env.AUTH_SPOTIFY_SECRET,
}),
],
callbacks: {
async jwt({ token, account }) {
if (account) {
return {
...token,
access_token: account.access_token,
refresh_token: account.refresh_token,
expires_at: account.expires_at,
};
}
// Return previous token if not expired
if (Date.now() < (token.expires_at as number) * 1000) {
console.log(
`expiriing at ${
(((new Date((token.expires_at as any) * 1000) as any) -
Math.floor(Date.now())) as any) /
(60 * 1000)
} minutes`
);
return token;
}
// Token expired, try refreshing
try {
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${Buffer.from(
`${process.env.AUTH_SPOTIFY_ID}:${process.env.AUTH_SPOTIFY_SECRET}`
).toString("base64")}`,
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: token.refresh_token as any,
}),
});
const tokens = await response.json();
if (response.ok) {
("no error on response");
}
console.log(" token:", tokens);
return {
...token,
access_token: tokens.access_token,
expires_at: Math.floor(Date.now() / 1000 + tokens.expires_in),
refresh_token: tokens.refresh_token ?? token.refresh_token,
};
} catch (error) {
// Force sign out if refresh fails
return { ...token, error: "RefreshAccessTokenError" };
}
},
async session({ session, token }) {
return {
...session,
access_token: token.access_token,
refesh_token: token.refresh_token,
};
},
},
});
Upvotes: 0
Views: 84