-
Notifications
You must be signed in to change notification settings - Fork 1
Feat/#108 middleware에서 refreshToken을 이용한 accessToken 자동 갱신 로직 추가 #116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
43f0e78
feat: middleware에서 accessToken 자동 갱신 로직 추가
leeleeleeleejun 017aa3a
fix: 경로 import를 app/_constants에서 @/_constants로 수정
leeleeleeleejun 1d43299
fix: accessToken 쿠키 옵션 sameSite 및 expires로 수정
leeleeleeleejun 75ef32e
fix: 백엔드에서 여러 Set-Cookie 헤더를 올바르게 포워딩하도록 수정
leeleeleeleejun 28a93df
fix: accessToken 쿠키 설정 시 옵션(path, secure, sameSite, expires) 추가
leeleeleeleejun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,32 +1,93 @@ | ||
| import { NextRequest, NextResponse } from 'next/server' | ||
| import { cookies } from 'next/headers' | ||
| import { CLIENT_PATH } from 'app/_constants/path' | ||
| import { API_PATH, CLIENT_PATH } from '@/_constants/path' | ||
|
|
||
| export async function middleware(request: NextRequest) { | ||
| const cookieStore = await cookies() | ||
| const accessToken = cookieStore.get('accessToken')?.value | ||
| const accessToken = request.cookies.get('accessToken')?.value | ||
| const refreshToken = request.cookies.get('refreshToken')?.value | ||
|
|
||
| if (!accessToken) { | ||
| // [Case 1] 액세스 토큰이 유효한 경우 -> 가장 먼저 통과시킴 (Early Return) | ||
| if (accessToken) { | ||
| return NextResponse.next() | ||
| } | ||
|
|
||
| // [Case 2] 토큰이 아예 없는 경우 -> 곧바로 로그인 페이지로 (Early Return) | ||
| if (!refreshToken) { | ||
| return NextResponse.redirect(new URL(CLIENT_PATH.LOGIN, request.url)) | ||
| } | ||
|
|
||
| return NextResponse.next() | ||
| // [Case 3] 액세스 토큰 만료 & 리프레시 토큰 존재 -> 갱신 시도 | ||
| return await handleTokenRefresh(request, refreshToken) | ||
| } | ||
|
|
||
| export const config = { | ||
| matcher: [ | ||
| '/likes', | ||
| '/profile', | ||
|
|
||
| // '/places/new', | ||
| // '/places/new/success', | ||
| // '/places/new/fail', | ||
|
|
||
| '/requests', | ||
| '/requests/:path*', | ||
|
|
||
| '/events/lucky-draw', | ||
| '/events/gifticon', | ||
| '/events/gifticon/:path*', | ||
| ], | ||
| } | ||
|
|
||
| const handleTokenRefresh = async ( | ||
| request: NextRequest, | ||
| refreshToken: string, | ||
| ) => { | ||
| try { | ||
| const response = await fetch( | ||
| `${process.env.NEXT_PUBLIC_API_URL}${API_PATH.AUTH.TOKEN}`, | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| Cookie: `refreshToken=${refreshToken}`, | ||
| }, | ||
| }, | ||
| ) | ||
|
|
||
| if (!response.ok) throw new Error('Token refresh failed') | ||
|
|
||
| // 구조 분해 할당을 한 번에 처리하여 코드 간소화 | ||
| const { | ||
| data: { accessToken: newAccessToken, accessTokenExpiresIn }, | ||
| } = await response.json() | ||
|
|
||
| // 1. [서버 컴포넌트 동기화] Request Header 조작 | ||
| const requestHeaders = new Headers(request.headers) | ||
| requestHeaders.set('Authorization', `Bearer ${newAccessToken}`) | ||
|
|
||
| const res = NextResponse.next({ | ||
| request: { | ||
| headers: requestHeaders, | ||
| }, | ||
| }) | ||
|
|
||
| // 2. [브라우저 동기화] 쿠키 세팅 | ||
| res.cookies.set('accessToken', newAccessToken, { | ||
| path: '/', | ||
| secure: process.env.NODE_ENV === 'production', | ||
| sameSite: 'lax', | ||
| expires: new Date(Date.now() + accessTokenExpiresIn), | ||
| }) | ||
|
|
||
| // 3. 백엔드 쿠키(Set-Cookie) 포워딩 | ||
| const backendSetCookies = response.headers.getSetCookie() | ||
| for (const cookie of backendSetCookies) { | ||
| res.headers.append('set-cookie', cookie) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| return res | ||
| } catch (error) { | ||
| console.error('Middleware Token Refresh Error:', error) | ||
|
|
||
| // 갱신 실패 시 로그인 리다이렉트 및 만료 토큰 정리 | ||
| const redirectRes = NextResponse.redirect( | ||
| new URL(CLIENT_PATH.LOGIN, request.url), | ||
| ) | ||
| redirectRes.cookies.delete('refreshToken') | ||
|
|
||
| return redirectRes | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.