admin管理员组文章数量:1129451
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:
" 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(";, {
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,
};
},
},
});
本文标签: typescripthow do i refresh an access token in authjs or nextauthStack Overflow
版权声明:本文标题:typescript - how do i refresh an access token in auth.js or next-auth - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736738856a1950399.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论