首页 > 解决方案 > 使用 JWT 响应持久登录

问题描述

我有一个使用有效身份验证在 React 客户端/Express API 中创建的应用程序。我可以注册、登录等。

现在我正在尝试使用 JWT 令牌添加持久登录,这样如果用户打开 URL,它将立即将他们定向到 Web 应用程序的主页。

拳头我正在从src/services/api我的 Reactapp 中导出令牌功能

api.js

export const getToken = () => {
  const token = localStorage.getItem('authToken');
  api.defaults.headers.common.authorization = (token && `Bearer ${token}`) || '';
  return token;
};

然后我将它传递给 App.js

应用程序.js

import { getToken } from './services/api'

并进入渲染方法App.js

  render() {
    //Persistent Login: Send user to dashboard if already authenticated
    const isAuthenticated = getToken()
    if (isAuthenticated) {
      return <Redirect to="/dashboard" />
    }

问题是,如果我关闭网页并打开它,它会重定向但它会进入一个空白屏幕。控制台或网络选项卡中没有数据显示任何类型的错误。

我可以在Chrome > Inspector Tools > Application> Local Storage的本地存储中看到令牌。

KEY                 VALUE
authToken           someTokenLikeiIsInR5cCI6IkpXVCJ9

如果我删除 的渲染方法中的代码App.js,我可以看到我的页面布局。

我对 React 和会话处理还比较陌生。我在网上找到的大部分信息都与 React + Redux(我还没有使用过)有关,所以我被卡住了。

任何想法为什么屏幕返回空白?任何建议/解决方案都会非常棒,谢谢。

标签: javascriptreactjsjwt

解决方案


看起来你在检查过程中得到了一个无限循环

render() {
    //Persistent Login: Send user to dashboard if already authenticated
    const isAuthenticated = getToken()
    if (isAuthenticated) {
      return <Redirect to="/dashboard" />
    }

每次当 isAuthenticated === true 时,用户被重定向到另一个页面并且应用程序正在重新渲染。因此,每次应用程序重新渲染时,它都会检查条件,因此会出现无限循环。我认为你可以添加一个额外的条件来避免这个循环。

render() {
    //Persistent Login: Send user to dashboard if already authenticated
    const isAuthenticated = getToken()
    if (isAuthenticated && history.location.pathname !== "/dashboard") {
      return <Redirect to="/dashboard" />
    }


推荐阅读