카테고리 없음

[백엔드,프론트엔드] JWT 토큰 유효시간 변경 -> 토큰 만료 후 접근 시 로그인 페이지로 이동

죠으닝 2024. 1. 4. 13:55

 5초로 변경함

app.jwt.expiration-in-ms=5000

 

로그인 후 구매버튼 클릭하면 이미 토큰이 만료가돼서 

예상치 못한 에려가 발생했다고 뜸

 

 

 

 

 

 

base.service.js

import axios from "axios";
import store from "../store/configStore";
import { clearCurrentUser } from "../store/actions/user";

import { useNavigate } from "react-router-dom";

const authHeader = () => {
  const currentUser = store.getState().user;

  return {
    "Content-Type": "application/json",
    authorization: "Bearer " + currentUser?.token,
  };
};

const handleResponseWithLoginCheck = () => {
  //에러 발생했을 때 인터셉터가 먼저 에러를 캐치함
  axios.interceptors.response.use(
    (response) => response,
    (error) => {
      const currentUser = store.getState().user;
      const isLoggedIn = currentUser?.token;
      const status = error?.response?.status;
      if (isLoggedIn && [401, 403].includes(status)) {
        store.dispatch(clearCurrentUser());
        window.location.href = "/login";
      }
      return Promise.reject(error);
    }
  );
};

export { authHeader, handleResponseWithLoginCheck };

 

 

main.jsx에 적용 

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import { Provider } from "react-redux";
import store from "./store/configStore.js";
import { handleResponseWithLoginCheck } from "./services/base.service.js";

//로그인체크 -> 에러 발생 시
handleResponseWithLoginCheck();

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    {/* 리듀서 적용 */}
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

 

 

토큰 만료 후 구매를 하려고 하면 

 

로그인 페이지로 이동함

 

 

이제 5초에서 30분으로 토큰 유효시간 수정한다. 

#30
app.jwt.expiration-in-ms=180000