How to handle expired jwt token in react redux?

Viewed 5426

I'm developing the application with react js and redux. For backend i used java to create api's. So far i have created three services, login, signup, listing. I have used jwt token for listing service to secure the incformation. I have set jwt token expiration time is 10 mins in backend. Each 10 mins the jwt token will get expired and for new token i need to login again. This is what i have done in backend.

I have integrated those services in my react with redux concept. The problem which i'm getting is, each i need to go login screen for new token. I want this to be happen in 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)));
}
0 Answers
Related