Skip to content

Commit 8b87b1f

Browse files
authored
Merge pull request #50 from junotb/fix/2026-02-13
fix: 크로스 오리진 API 인증 시 Bearer 토큰 사용
2 parents 9eb40b6 + 80c88ca commit 8b87b1f

2 files changed

Lines changed: 21 additions & 17 deletions

File tree

web/src/lib/__tests__/api.test.ts

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import api from '../api';
22

3+
jest.mock('@/lib/auth-client', () => ({
4+
authClient: {
5+
getSession: jest.fn().mockResolvedValue({ data: null }),
6+
},
7+
}));
8+
39
/**
410
* API Client 단위 테스트
5-
* 쿠키 기반 인증으로 전환 후 Bearer Token 추출 로직이 제거되었는지 확인합니다.
11+
* 프로덕션 크로스 오리진 환경에서 Bearer 토큰으로 인증합니다.
612
*/
713
describe('API Client', () => {
814
describe('Axios 설정', () => {
@@ -20,20 +26,9 @@ describe('API Client', () => {
2026
});
2127

2228
describe('요청 인터셉터', () => {
23-
it('should not have request interceptors that set Authorization header', () => {
24-
// Bearer Token 추출 로직이 제거되었으므로
25-
// 요청 인터셉터가 없거나 Authorization 헤더를 설정하지 않아야 함
29+
it('should have request interceptor for Bearer token', () => {
2630
const requestInterceptors = api.interceptors.request.handlers;
27-
28-
// 요청 인터셉터가 없거나, Authorization 헤더를 설정하지 않는지 확인
29-
if (requestInterceptors.length > 0) {
30-
// 인터셉터가 있다면 Authorization 헤더를 설정하지 않는지 확인
31-
// 실제로는 인터셉터가 없어야 함 (Bearer Token 로직 제거됨)
32-
expect(requestInterceptors.length).toBe(0);
33-
} else {
34-
// 인터셉터가 없는 것이 정상 (Bearer Token 로직 제거됨)
35-
expect(requestInterceptors.length).toBe(0);
36-
}
31+
expect(requestInterceptors.length).toBeGreaterThan(0);
3732
});
3833
});
3934

web/src/lib/api.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import axios, { AxiosError } from "axios";
22
import type { ApiError, ApiErrorResponse } from "@/types/api";
33
import { API_URL } from "@/constants/api";
4+
import { authClient } from "@/lib/auth-client";
45

56
// 하위 호환성을 위해 타입 re-export
67
export type { ApiError, ApiErrorResponse } from "@/types/api";
@@ -10,11 +11,19 @@ const api = axios.create({
1011
headers: {
1112
"Content-Type": "application/json",
1213
},
13-
withCredentials: true, // 쿠키 자동 전송 (Better-Auth 세션 쿠키 포함)
14+
withCredentials: true,
1415
});
1516

16-
// Bearer Token 추출 로직 제거
17-
// 쿠키가 자동으로 전송되므로 추가 작업 불필요
17+
// 프로덕션: Web/API 도메인이 달라 쿠키 미전송 → Bearer 토큰으로 인증
18+
api.interceptors.request.use(async (config) => {
19+
if (typeof window === "undefined") return config;
20+
21+
const { data: session } = await authClient.getSession();
22+
if (session?.session?.token) {
23+
config.headers.Authorization = `Bearer ${session.session.token}`;
24+
}
25+
return config;
26+
});
1827

1928
api.interceptors.response.use(
2029
(response) => response,

0 commit comments

Comments
 (0)