小编eva*_*ine的帖子

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

目前,当我创建路由时,我会检查 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" />
        )}
      />
Run Code Online (Sandbox Code Playgroud)

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() …
Run Code Online (Sandbox Code Playgroud)

authentication cookies reactjs auth0 react-router-v4

6
推荐指数
1
解决办法
2249
查看次数