简体   繁体   中英

How to keep the user logged in after a Refresh in auth0-js?

Authentication.js:

silentAuth() {
  return new Promise((resolve, reject) => {
    this.auth0.checkSession({}, (err, authResult) => {
      console.log("Auth result: " + authResult);
      if (err) return reject(err);
      this.setSession(authResult);
      resolve();
    });
  });
}

setSession(authResult, step) {
  this.idToken = authResult.idToken;
  this.profile = authResult.idTokenPayload;
  // set the time that the id token will expire at
  this.expiresAt = authResult.expiresIn * 1000 + new Date().getTime();
}

Inside the App component:

async componentDidMount() {
  if (this.props.location.pathname === '/callback') return;
  try {
    await auth0Client.silentAuth();
    this.forceUpdate();
  } catch (err) {
    if (err.error === 'login_required') return;
    console.log("ERROR: " + err.error);
  }
}

What I expect is that unless I logged out from the app, checkSession must return a valid authResult but it returns undefined when I refresh the page? So I want the user to keep logged in after Refresh?

How about using something like localStorage to store your state?

localStorage.setItem("loggedIn", true)

....

localStorage.getItem("loggedIn")

Your authResult should contain different fields including:

  • idToken
  • access_token
  • expiresAt
  • ...

I would recommmend to store those values in your LocalStorage or SessionStorage on login and retrieve it on application state. I would not recommend to store loggedIn with a boolean value since this might has changed according to the expiresAt attribute. So an isAuthenticated in your AuthService that determines the current real state according to the availability of access_token and expiresAt in the context of the current time would be the appropriate way to go.

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