prosource

토큰 유효기간 및 로그아웃 사용자를 확인하려면 어떻게 해야 합니까?

probook 2023. 2. 12. 18:01
반응형

토큰 유효기간 및 로그아웃 사용자를 확인하려면 어떻게 해야 합니까?

로그아웃 버튼을 클릭하면 사용자가 직접 로그아웃할 수 있지만, 내 어플리케이션에서는 토큰이 서버 측과 프런트 엔드에서 모두 사용되기 때문에 토큰이 만료되면 로그아웃할 수 없습니다.사용자가 로그아웃 버튼을 클릭하면 토큰이 유효한 경우 서버와 브라우저 모두에서 토큰이 지워집니다.사용자가 로그아웃하지 않고 토큰이 만료되었지만 브라우저에서 지워지지 않을 수 있습니다.이 상황을 해결하려면 사용자가 앱에 방문할 때마다 토큰 만료 여부를 확인하고 토큰이 만료되면 브라우저에서 토큰을 지우려면 어떻게 해야 합니까?

사용자가 페이지를 갱신하거나 다른 페이지로 전환할 때마다 백그라운드에서 시청하는 사가를 시도했습니다.이건 효율적인 방법이 아닌 것 같아요.미들웨어가 유행하는 것 같아요.

function* loadInitialActions() {
  var dateNow = new Date();
  console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (
    token &&
    jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
  ) {
    yield put(LOGOUT_SUCCESS);
  }
}

function* initialize() {
  const watcher = yield fork(loadInitialActions);
  yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
  yield cancel(watcher);
}

function* rootSaga() {
  console.log("rootSaga");
  yield takeLatest(INITIALIZE, initialize);
}

따라서 미들웨어에서 토큰이 만료되었을 경우 토큰 만료 로직과 로그아웃 사용자를 어떻게 사용할 수 있습니까?

제 생각에는 미들웨어가 최선의 선택이 될 것 같습니다.

이런 거 할 수 있어요.

const checkTokenExpirationMiddleware = store => next => action => {
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (jwtDecode(token).exp < Date.now() / 1000) {
    next(action);
    localStorage.clear();
  }
  next(action);
};

그 다음에 그걸 싸서applyMiddleware

const parseJwt = (token) => {        
    const decode = JSON.parse(atob(token.split('.')[1]));
    console.log(decode);
    if (decode.exp * 1000 < new Date().getTime()) {
        logoutAction();
        console.log('Time Expired');
    }
};

메인 컴포넌트를 HOC로 랩해야 합니다.HOC는 토큰을 검증하고 정상일 경우 컴포넌트 표시를 허용합니다.토큰이 비활성화되면 로그인 페이지가 로 리다이렉트 됩니다.

const authChecker = (Component) => {
  return class extends React.Component {
    state = {
      show: false;
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.children !== this.props.children) {
        this.checkAuth();
      }
    }

    componentDidMount() {
      this.checkAuth();
    }

    checkAuth() {
      Api.checkAuth()
      .then(result => {
        if (result.success) {
          this.setState({ show: true });
        } else {
          // logout since token expired
          API.logout();
        }
      });
    }

    render() {
      return this.state.show && <Component {...this.props} />
    }
  }
}

export default authChecker(Main);

this.serverResponse.expires_in는 유효기간(초단위)입니다.

var tokenexpiration: Date = new Date();
tokenexpiration.setSeconds(new Date().getSeconds() + parseInt(this.serverResponse.expires_in))
console.log(tokenexpiration);

localStorage에 저장할 수 없습니다.

localStorage.setItem('expirationdate',tokenexpiration)

간단한 조건으로 토큰의 유효기간이 지났는지 여부를 언제든지 확인할 수 있습니다.

언급URL : https://stackoverflow.com/questions/44982412/how-do-i-check-for-token-expiration-and-logout-user

반응형