Skip to content

Commit a89091d

Browse files
yellowjang장아영KingNono1030
authored
[#179] ✨ 미들웨어에서 토큰 갱신 (#190)
* [#179] 📦 install jsonwebtoken * [#179] ✨ requestNewToken in middleware * [#179] ♻️ refactor middleware * [#179] 🐛 working on middleware token issue * [#179] ♻️ refactor unused code * [#179] ✨ add middleware deliver accessToken, refreshToken, and requestNewToken() * [#179] ♻️ separate requestNewToken function * [#179] ✨ add TokenApiResponse type * [#179] ♻️ refactor and apply constants * [#179] ♻️ delete duplicated code * [#179] ♻️ change token expired time --------- Co-authored-by: 장아영 <[email protected]> Co-authored-by: KingNono1030 <[email protected]>
1 parent 277a7b7 commit a89091d

File tree

13 files changed

+208
-127
lines changed

13 files changed

+208
-127
lines changed

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
{
22
"dependencies": {
33
"@tanstack/react-query": "^5.59.19",
4+
"@types/jsonwebtoken": "^9.0.7",
45
"clsx": "^2.1.1",
56
"es-hangul": "^2.2.4",
7+
"jsonwebtoken": "^9.0.2",
68
"ky": "^1.7.2",
79
"next": "^15.0.2",
810
"react": "^18.3.1",

pnpm-lock.yaml

Lines changed: 90 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/app/(pages)/protected/page.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
'use client'
2+
13
export default function protectedPage(): JSX.Element {
24
return (
35
<>

src/app/api/auth/refresh/route.ts

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,48 @@
1-
import { NextResponse } from 'next/server'
1+
import { NextRequest, NextResponse } from 'next/server'
22

3+
import { ApiResponse } from '@/types/api/ApiResponse.types'
4+
import { AccessTokenResponse } from '@/types/api/Auth.types'
35
import { HTTPError } from 'ky'
46

57
import { backendApi } from '@/services/api'
68

7-
export const POST = async (req: Request): Promise<NextResponse> => {
8-
const { refreshToken } = await req.json()
9+
export const POST = async (req: NextRequest): Promise<NextResponse> => {
10+
const body = await req.json()
11+
const { oldAccessToken, refreshToken } = body
912

1013
try {
11-
const { accessToken } = await backendApi
12-
.post('refresh', { json: { refreshToken } })
13-
.json<{ accessToken: string }>()
14-
return NextResponse.json({ success: true, accessToken })
14+
const {
15+
result: { accessToken },
16+
} = await backendApi
17+
.post('v1/auth/new-token', {
18+
json: { oldAccessToken, refreshToken },
19+
headers: {
20+
Authorization: `Bearer ${refreshToken}`, // 필요하다면 추가
21+
},
22+
})
23+
.json<ApiResponse<AccessTokenResponse>>()
24+
25+
const res = NextResponse.json({ success: true, result: { accessToken } })
26+
27+
res.cookies.set('accessToken', accessToken, {
28+
httpOnly: true,
29+
secure: process.env.NODE_ENV === 'production',
30+
sameSite: 'lax',
31+
path: '/',
32+
maxAge: 1800, // 30 minutes
33+
})
34+
35+
console.log('새로운 토큰 갱신 성공')
36+
console.log(accessToken)
37+
38+
return res // 성공 응답 반환
1539
} catch (error: unknown) {
16-
console.error('토큰 갱신 에러:', error)
1740
if (error instanceof HTTPError) {
1841
const errorData = await error.response.json()
1942
return NextResponse.json(
2043
{
2144
success: false,
22-
message: errorData.messassage || '토큰 갱신 실패',
45+
message: errorData.message || '토큰 갱신 실패',
2346
},
2447
{ status: error.response.status }
2548
)

src/app/api/auth/sign-in/route.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { NextResponse } from 'next/server'
22

3+
import { ApiResponse } from '@/types/api/ApiResponse.types'
34
import { SignInRequest, SignInResponse } from '@/types/api/Auth.types'
45
import { HTTPError } from 'ky'
56

src/app/api/auth/validate/route.ts

Lines changed: 0 additions & 67 deletions
This file was deleted.

src/constants/auth.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const tokenBufferTime = 1 * 60 * 1000
2+
export const tokenExpiredTime = 2 * 60 * 1000
3+
4+
export const middlewareBufferTime = 5 * 60
5+
export const middlewareExpiredTime = 60 * 60

0 commit comments

Comments
 (0)