jwt 로그인 구현 진행 : axios 로 api 호출하여 생성된 쿠키로 인증상태값 변경기능 구현

This commit is contained in:
2025-12-31 19:39:42 +09:00
parent fd40ce5e75
commit 985ba75d34
12 changed files with 340 additions and 35 deletions

83
src/axios/authService.ts Normal file
View File

@@ -0,0 +1,83 @@
import axios from './axios';
import { jwtDecode } from 'jwt-decode';
export const getAccessTokenFromCookie = (): string | null => {
const name = 'access_token';
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
return null;
};
export interface LoginCredentials {
memberId: string;
password: string;
}
export interface RegisterData {
username: string;
email: string;
password: string;
}
export interface AuthResponse {
resultCode: string;
resultMessage: string;
resultData: string;
}
export interface DecodedToken {
encryptedPayload: string;
memberId: string;
memberName: string;
expiration: number;
}
// 로그인 API
export const login = async (credentials: LoginCredentials): Promise<AuthResponse> => {
const response = await axios.post<AuthResponse>('/auth/login', credentials);
return response.data;
};
// 회원가입 API
export const register = async (data: RegisterData): Promise<{ message: string }> => {
const response = await axios.post<{ message: string }>('/auth/register', data);
return response.data;
};
// 로그아웃 API
export const logout = async (): Promise<void> => {
await axios.post('/auth/logout');
//localStorage.removeItem('access_token');
//localStorage.removeItem('refresh_token');
document.cookie = 'access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';
document.cookie = 'refresh_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/';
};
// 토큰이 유효한지 확인
export const isTokenValid = (token: string): boolean => {
try {
const decoded = jwtDecode<DecodedToken>(token);
const currentTime = Date.now() / 1000;
return decoded.expiration > currentTime;
} catch (error) {
return false;
}
};
// 토큰에서 사용자 정보 추출
export const getUserFromToken = (token: string): DecodedToken | null => {
try {
const decoded = jwtDecode<DecodedToken>(token);
return decoded;
} catch (error) {
return null;
}
};
// 현재 사용자 정보 가져오기
export const getCurrentUser = async () => {
const response = await axios.get('/auth/me');
return response.data;
};

26
src/axios/axios.ts Normal file
View File

@@ -0,0 +1,26 @@
import axios from 'axios';
const API_URL = '/api/v1/';
// Axios 인스턴스 생성
const instance = axios.create({
baseURL: API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
});
// 요청 인터셉터
instance.interceptors.request.use(
(config) => {
const accessToken = localStorage.getItem('access_token');
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
},
(error) => Promise.reject(error)
);
export default instance;