简体   繁体   中英

Storing and retrieving session Laravel Passport Token in React SPA App

I want to implement a simple SPA app with Passport Auth API,

I tried localStorage (in js) to store the token there, but it seems not secure. So I was looking for alternative.

btw. Laravel 5.8 react 16.8

export const LogIn = formValues => async dispatch => {
    connect.post('auth/login', formValues).then(response => {
        return response;
      })
      .then(json => {
        if (json.status === 200) {
         // alert("Login Successful!");

          let userData = {
            email: formValues.email,
            auth_token: json.data.access_token,
            timestamp: new Date().toString()
          };

          let appState = {
            isLoggedIn: true,
            user: userData
          };

          // save app state with user date in local storage
          localStorage["appState"] = JSON.stringify(appState);

          return userData;

        } else alert("Login Failed!");

      })
      .catch(error => {
        let appState = {
          isLoggedIn: false,
          user: {}
        };

        localStorage["appState"] = JSON.stringify(appState);

        alert(`An Error Occured! ${error}`);
      });
};

I can Login and Logout from my APP. Only upon refresh I am losing the tokens. I am lost here for 2 weeks already :(

What you need to to is to persist your authenticated state.

You can do this by creating a context provider and accessing the values inside your component (check out React Redux Connect API or check out React Context API )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM