From b1ba030a7e9fea28bf4bc916c845b8fc074caa90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=86=8C=EC=9A=B8=EC=B9=98=ED=82=A8?= <90738604+soulchicken@users.noreply.github.com> Date: Wed, 11 Oct 2023 00:16:52 +0900 Subject: [PATCH] =?UTF-8?q?Feat:=20refresh=20=ED=86=A0=ED=81=B0=EC=9D=84?= =?UTF-8?q?=20=ED=99=9C=EC=9A=A9=ED=95=B4=EC=84=9C=20accessToken=20?= =?UTF-8?q?=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pages/api/auth/[...nextauth].ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/pages/api/auth/[...nextauth].ts b/src/pages/api/auth/[...nextauth].ts index 70747f4..e818a66 100644 --- a/src/pages/api/auth/[...nextauth].ts +++ b/src/pages/api/auth/[...nextauth].ts @@ -5,7 +5,8 @@ import GoogleProvider from 'next-auth/providers/google'; import NaverProvider from 'next-auth/providers/naver'; import KakaoProvider from 'next-auth/providers/kakao'; import CredentialsProvider from 'next-auth/providers/credentials'; -import { credentialsLoginAPI, socialLoginAPI } from '@/utils/api/accounts'; +import { credentialsLoginAPI, refreshAccessToken, socialLoginAPI } from '@/utils/api/accounts'; +import { isTokenExpired } from '@/utils/services/auth'; interface CustomSession extends Session { accessToken: string | null; @@ -101,12 +102,38 @@ export const authOptions: NextAuthOptions = { if (user?.refreshToken) { token.refreshToken = user.refreshToken; } + + // accessToken 만료를 검사합니다. + if (token.accessToken && isTokenExpired(token.accessToken as string)) { + // 만료된 경우 refreshToken으로 새 accessToken을 발급 + const newAccessToken = await refreshAccessToken(token.accessToken as string); + if (newAccessToken) { + token.accessToken = newAccessToken; // 새로운 accessToken으로 업데이트 + } else { + // TODO: refresh token 만료시 추가 처리 + // refreshToken도 만료되었거나 문제가 있을 경우 + // 필요한 추가 처리 (로그아웃)를 여기에다가 작성 + } + } + return token; }, async session({ session, token }: SessionCallback) { (session as CustomSession).accessToken = token.accessToken as string | null; (session as CustomSession).refreshToken = token.refreshToken as string | null; + + if (session.accessToken && isTokenExpired(session.accessToken)) { + // 만료된 경우 refreshToken으로 새 accessToken을 발급받습니다. + const newAccessToken = await refreshAccessToken(session.refreshToken as string); + + if (newAccessToken) { + session.accessToken = newAccessToken; + } + // TODO: refresh token 만료시 추가 처리 + // refreshToken도 만료되었거나 문제가 있을 경우 + // 필요한 추가 처리 (로그아웃)를 여기에다가 작성 + } return session; },