如何在浏览器中为React SPA保留Auth0登录状态

问题描述 投票:1回答:1

目前,当我创建路由时,我检查一个Auth0方法 - isAuthenticated() - 来确定是否返回受保护的页面或重定向到登录。但是,此状态仅存在于内存中,并且在浏览器刷新时不会将用户保留在其页面上,我希望这样做。

这是一个React / RR4 / React Context应用程序,我的Auth0方法列在Auth.js(下面)中。

在localStorage中存储登录状态是非常不明智的。如果我将我的Auth0令牌存储在cookie中,我不确定如何验证令牌,因为没有设置服务器验证。检查将启用安全数据持久性的正确条件是什么?

ProtectedRoutes.jsx:

   <Route
      exact
      key={route.path}
      path={route.path}
      render={() => (
        // CONDITION TO CHECK
        context.auth.isAuthenticated()
          ? (
            <div>
              <route.component />
            </div>
          ) : <Redirect to="/login" />
        )}
      />

Auth.js(已添加供参考):

import auth0 from 'auth0-js';
import authConfig from './auth0-variables';

class Auth {
  accessToken;
  idToken;
  expiresAt;
  tokenRenewalTimeout;

  auth0 = new auth0.WebAuth({
    domain: authConfig.domain,
    clientID: authConfig.clientId,
    redirectUri: authConfig.callbackUrl,
    responseType: 'token id_token',
    scope: 'openid'
  });

  constructor() {
    this.scheduleRenewal();
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getIdToken = this.getIdToken.bind(this);
    this.renewSession = this.renewSession.bind(this);
    this.scheduleRenewal = this.scheduleRenewal.bind(this);
  }

  login() {
    console.log('logging in!');
    this.auth0.authorize();
  }

  handleAuthentication() {
    return new Promise((resolve, reject) => {
      this.auth0.parseHash((err, authResult) => {
        if (err) return reject(err);
        console.log(authResult);
        if (!authResult || !authResult.idToken) {
          return reject(err);
        }
        this.setSession(authResult);
        resolve();
      });
    });
  }

  getAccessToken() {
    return this.accessToken;
  }

  getIdToken() {
    return this.idToken;
  }

  getExpiration() {
    return new Date(this.expiresAt);
  }

  isAuthenticated() {
    let expiresAt = this.expiresAt;
    return new Date().getTime() < expiresAt;
  }

  setSession(authResult) {
    localStorage.setItem('isLoggedIn', 'true');
    let expiresAt = (authResult.expiresIn * 1000) + new Date().getTime();
    this.accessToken = authResult.accessToken;
    this.idToken = authResult.idToken;
    this.expiresAt = expiresAt;
    this.scheduleRenewal();
  }

  renewSession() {
    this.auth0.checkSession({}, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        this.logout();
        console.log(`Could not get a new token. (${err.error}: ${err.error_description})`);
      }
    });
  }

  scheduleRenewal() {
    let expiresAt = this.expiresAt;
    const timeout = expiresAt - Date.now();
    if (timeout > 0) {
      this.tokenRenewalTimeout = setTimeout(() => {
        this.renewSession();
      }, timeout);
    }
  }

  logout() {
    this.accessToken = null;
    this.idToken = null;
    this.expiresAt = 0;
    localStorage.removeItem('isLoggedIn');
    clearTimeout(this.tokenRenewalTimeout);
    console.log('logged out!');
  }
}

export default Auth;
reactjs authentication cookies react-router-v4 auth0
1个回答
1
投票

您可以使用Silent authentication在浏览器刷新时更新令牌。

专门为您的反应SPA应用程序

  • 在你的主App组件中设置一个状态,说tokenRenewedfalse
  • 你已经在你的renewToken中有一个auth.js方法所以在componentDidMount方法中调用它
componentDidMount() {
   this.auth.renewToken(() => {
      this.setState({tokenRenewed : true});
   })
}
  • 更新renewToken接受如下所示的回调cb
renewSession(cb) {
    this.auth0.checkSession({}, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
      } else if (err) {
        this.logout();
        console.log(`Could not get a new token. (${err.error}: ${err.error_description})`);
      }
      if(cb) cb(err, authResult);
    });
  }
  • 确保您不加载App组件,除非tokenRenewedtrue,即除非您通过静默认证更新了有效的令牌
render() {
    if(!this.state.tokenRenewed) return "loading...";
    return (
      // Your App component
    );
}

笔记:

  1. 您可能需要确保在应用程序设置中设置了正确的Allowed Web Origins才能使其正常工作
  2. 静默身份验证有一些限制,因为它需要在浏览器上启用第三方cookie,以及在ITP for Safari中使用。您应该设置自定义域以避免这种情况。请参阅官方auth0文档以了解更多here
  3. 关于如何安全地存储令牌here的更多细节
© www.soinside.com 2019 - 2024. All rights reserved.