How to deal with expired jwt token in react redux?

I am developing an app using js and redux. For the backend, I used java to create the api. So far I have created three services, login, registration, listing. I have used the jwt token to provide information protection services. I have set the jwt token expiration time to 10 minutes in the backend. Every 10 minutes the jwt token expires and for a new token I need to login again. This is what I did in the backend.

I have included these services in my react with the redux concept. The problem I am getting is I need to go to the login screen for a new token. I want this to happen in the background. How to do with redux?

export function handleResponse(response) {
  if (response.ok) {
    return response.json();
  }
  // If invalid jwt token the page will get redirect to login.
  if (response.status === 401) {
    localStorage.clear();
    alert('Session expired!');
    location.href = '/login';
  }
}

export function loginAction(data) {
  const resObject = {
    username: data.username,
    password: data.password,
  };
  return dispatch =>
    fetch(`/login`, {
      method: 'post',
      body: JSON.stringify(resObject),
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Basic ${basicAuth.authSecret}`,
      },
    })
      .then(handleResponse)
      .then(res => dispatch(loginUser(res)));
}

      

+3


source to share





All Articles