Using session cookies in action

I have a question about session cookies in React.

I am currently performing user authentication:

export function loginUser({ email, password }) {
    return function(dispatch) {
        axios.post(`${API_URL}/users/authenticate`, { email, password }, { withCredentials: true })
            .then((response) => {
                if (response.data.result_status == "success") {
                    localStorage.setItem("token", JSON.stringify(response.data.user))
                        dispatch({ type: AUTHENTICATE_USER }); 
                        browserHistory.push("/home");
                    })
                } 
            })
            .catch(() => {
                dispatch(authError('Incorrect Login Info'));
            });
    }
}

      

I am sending email

and password

in the url. If response.data.result_status == "success"

, then I set the user's information (like their name and email address) to the localStorage token and I call AUTHENTICATE_USER

that sets the other localStorage object to true.

Since I am using localStorage, the data persists across reloads. And until the authenticated localStorage is set to null, I stay logged in.

However, we now want to stay logged in as LONG since the cookie session has not expired. I am currently staying logged in based on the token set for local storage, not a cookie.

The backend doesn't use JWT, only cookies. Is there a way to check if a cookie works with axioms?

+3


source to share


1 answer


The only one who knows that the session from the cookie is still active is the API, so on this side you will need to check if the session from the cookie is active. I am assuming you will get 401 Unauthenticated

if you are not already logged in so that you can check the response status code with every request and remove the localStorage item when the session expires.

I suggest you use the response from Axios to check the status code:



axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    if (error.status === 401) {
      // DELETE YOUR AUTHENTICATE_USER item from localStorage 
    }
    return Promise.reject(error);
});

      

+2


source







All Articles