Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Session Cookies in React

I have a question regarding session cookies in React.

Currently this is how I authenticate a user:

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 send the email and password to a url. If the response.data.result_status == "success", then I set the user info (like their name and email) to a localStorage token and I call AUTHENTICATE_USER which sets another localStorage item to true.

Since I'm using localStorage, the data persists when I reload. And as long as the authenticated localStorage is not set to null, I stay on the system.

However, now we want to stay on the system as LONG as the cookie's session is not expired. Currently I stay on the system based on the token I set to local storage, not the cookie.

The backend is not using JWT, just a cookie. Is there a way for me to check if the cookie is still in session with axios?

like image 533
lost9123193 Avatar asked Apr 10 '17 14:04

lost9123193


1 Answers

The only one who knows that the session from the cookie is still active is the API, therefor it's at this side you'll need to check whether the session from the cookie is still active. I assume you'll receive a 401 Unauthenticated when not logged in anymore so you could check the status code of the response with every request and remove the localStorage item when the session has expired.

I propose you'll use a response interceptor 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);
});
like image 65
Tom Van Rompaey Avatar answered Nov 10 '22 13:11

Tom Van Rompaey