하관우 하관우 03-21
2025-03-21 하관우 토큰재발급 완료료
@c6fbc4d9f945b95ed991b4ee9bc320d223500890
client/resources/api/index.js
--- client/resources/api/index.js
+++ client/resources/api/index.js
@@ -7,58 +7,78 @@
     }
 });
 
+// 요청 인터셉터
 apiClient.interceptors.request.use(
     config => {
-        config.headers.Authorization = store.state.authorization; // 요청 시 AccessToken 추가
+        const token = store.state.authorization; // Access Token 가져오기
+        if (token) {
+            config.headers.Authorization = token; // 단순히 토큰만 추가
+        }
         return config;
     },
     error => {
         return Promise.reject(error);
     }
-)
+);
 
+// 응답 인터셉터
 apiClient.interceptors.response.use(
     response => {
-        console.log('Response Status:', response.status); // 응답 상태 출력
         return response;
     },
     async error => {
-        console.log('Error Response:', error.response.data); // 오류 응답 데이터 출력
-        console.log('Error Status:', error.response.status); // 오류 상태 출력
-        if (error.response.status == 403 && error.response.data.message == '접근 권한이 없습니다.') {
-            window.history.back();
-        }
         const originalReq = error.config;
-        // 토큰의 만료기간이 끝난경우
-        if (error.response.status == 401 && error.response.data.message == '로그인 시간이 만료되었습니다.' && !originalReq._retry) {
-            originalReq._retry = true; // 재요청 시도(한번만 실행)
+
+        // 403 에러 처리
+        if (error.response.status === 403) {
+            alert('접근 권한이 없습니다.');
+            window.history.back();
+            return Promise.reject(error);
+        }
+
+        // 401 에러 처리 (토큰 만료)
+        if (error.response.status === 401 && error.response.data.message === '로그인 시간이 만료되었습니다.' && !originalReq._retry) {
+            // 토큰 재발급 요청
             try {
-                const res = await axios.post('/refresh/tknReissue.json', {});
-                store.commit('setAuthorization', res.headers.authorization); // 새로 발급 받은 AccessToken 저장
-                originalReq.headers.Authorization = store.state.authorization; // 새로 발급 받은 AccessToken을 기존 요청에 추가
-                /** jwt토큰 디코딩 **/
-                const base64String = store.state.authorization.split('.')[1];
-                const base64 = base64String.replace(/-/g, '+').replace(/_/g, '/');
-                const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
-                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
-                }).join(''));
-                const mbr = JSON.parse(jsonPayload);
-                // const mbr = JSON.parse(decodeURIComponent(escape(window.atob(base64String)))); // jwt claim 추출
-                store.commit("setUserNm", mbr.userNm);
-                store.commit('setRoles', mbr.roles);
-                /** jwt토큰 디코딩 **/
-                return apiClient(originalReq); // 원래 요청 재시도 /pathname + search
+                const res = await axios.post("/refresh/tknReissue.json", {}, {
+                    headers: {
+                        "Content-Type": "application/json; charset=UTF-8",
+                    },
+                });
+
+                // 응답 상태가 200일 경우에만 처리
+                if (res.status === 200) {
+                    // 새로 발급 받은 AccessToken 저장
+                    store.commit('setAuthorization', res.headers.authorization);
+                    originalReq.headers.Authorization = store.state.authorization; // 새로 발급 받은 AccessToken을 기존 요청에 추가
+
+                    // JWT 토큰 디코딩
+                    const base64String = store.state.authorization.split('.')[1];
+                    const base64 = base64String.replace(/-/g, '+').replace(/_/g, '/');
+                    const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
+                        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
+                    }).join(''));
+                    const mbr = JSON.parse(jsonPayload);
+                    store.commit("setUserNm", mbr.userNm); // 사용자 이름 저장
+                    store.commit('setRoles', mbr.roles); // 사용자 역할 저장
+
+                    return apiClient(originalReq); // 원래 요청 재시도
+                } else {
+                    // 200이 아닌 경우
+                    throw new Error("토큰 재발급 요청 실패");
+                }
             } catch (refreshError) {
                 const redirect = window.location.pathname + window.location.search;
                 sessionStorage.setItem("redirect", redirect);
                 alert('세션이 종료되었습니다.\n로그인을 새로 해주세요.');
                 store.commit("setStoreReset");
-                window.location = '/login.page';
+                window.location = '/login.page'; // 로그인 페이지로 리다이렉트
                 return Promise.reject(refreshError);
             }
         }
+
         return Promise.reject(error);
     }
-)
+);
 
-export default apiClient;
(파일 끝에 줄바꿈 문자 없음)
+export default apiClient;
client/views/App.vue
--- client/views/App.vue
+++ client/views/App.vue
@@ -1,4 +1,3 @@
-App.vue
 <template>
  <div class="wrapper">
     <Header />
client/views/pages/AppStore.js
--- client/views/pages/AppStore.js
+++ client/views/pages/AppStore.js
@@ -6,7 +6,6 @@
   plugins: [createPersistedState()],
   state: {
     authorization: null,
-    refresh: null, // 리프레시 토큰을 추가
     userId: null, // 사용자 ID 추가
     loginId: null, // 로그인 ID 추가
     userNm: null, // 사용자 이름 추가
@@ -15,9 +14,6 @@
   getters: {
     getAuthorization(state) {
       return state.authorization; // authorization 반환
-    },
-    getRefresh(state) {
-      return state.refresh; // 리프레시 토큰 반환
     },
     getUserNm(state) {
       return state.userNm; // 사용자 이름 반환
@@ -29,9 +25,6 @@
   mutations: {
     setAuthorization(state, newValue) {
       state.authorization = newValue; // authorization 설정
-    },
-    setRefresh(state, newValue) {
-      state.refresh = newValue; // 리프레시 토큰 설정
     },
     setLoginId(state, newValue) {
       state.loginId = newValue; // 로그인 ID 설정
@@ -47,7 +40,6 @@
     },
     setStoreReset(state) {
       state.authorization = null;
-      state.refresh = null; // 리프레시 토큰 초기화
       state.userNm = null;
       state.userId = null;
       state.roles = [];
client/views/pages/user/MyInfo.vue
--- client/views/pages/user/MyInfo.vue
+++ client/views/pages/user/MyInfo.vue
@@ -154,6 +154,8 @@
                             this.resetForm();
                             alert("비밀번호가 변경되었습니다.");
                             window.location.reload(); // 페이지 새로 고침
+                        } else {
+                            alert("비밀번호 변경이 실패되었습니다.");
                         }
                     }
                 }
@@ -167,6 +169,8 @@
                                 this.resetForm();
                                 alert("회원정보가 변경되었습니다.");
                                 window.location.reload(); // 페이지 새로 고침
+                            } else {
+                                alert("회원정보가 변경이 실패되었습니다.");
                             }
                         }
                     } else {
@@ -177,6 +181,8 @@
                                 this.resetForm();
                                 alert("회원과 비밀번호를 변경되었습니다.");
                                 window.location.reload(); // 페이지 새로 고침
+                            } else {
+                                alert("회원과 비밀번호 변경이 실패되었습니다.");
                             }
                         }
                     }
@@ -190,6 +196,8 @@
                                 this.resetForm();
                                 alert("비밀번호가 변경되었습니다.");
                                 window.location.reload(); // 페이지 새로 고침
+                            }else {
+                                alert("비밀번호 변경이 실패되었습니다.");
                             }
                         }
                     }
Add a comment
List