You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js搭配Laravel后端时路由保护失效,页面刷新后自动跳转登录页求助

问题排查及解决方案

核心问题根因

  • 登录状态仅存储在JS内存中,页面刷新后内存变量重置,isAuthenticated自动恢复为初始值false,路由守卫直接判定未登录跳转
  • 未校验后端真实登录状态,完全依赖前端状态判断,会出现前端状态和后端Session状态不一致的问题(如Session过期但前端仍显示已登录)
  • AuthProtection组件的useEffect未添加依赖项,可能触发异常逻辑

修复步骤

1. 修改Auth.js实现状态持久化

将登录状态同步存储到localStorage,页面刷新后从本地存储读取初始化状态:

const Auth = {
  // 初始化时优先读取本地存储的登录状态
  isAuthenticated: localStorage.getItem('is_authenticated') === 'true',
  authenticate() {
    this.isAuthenticated = true;
    localStorage.setItem('is_authenticated', 'true');
  },
  signout() {
    this.isAuthenticated = false;
    // 退出时清空所有相关本地存储
    localStorage.removeItem('is_authenticated');
    localStorage.removeItem('user-info');
  },
  getAuth() {
    return this.isAuthenticated;
  }
};

export default Auth;

2. 优化AuthProtection路由守卫逻辑

增加后端登录状态校验,避免前端状态和后端Session不一致的问题,同时添加加载态避免闪屏:

import React from 'react'
import { useHistory } from 'react-router'
import Auth from './Auth'
import axios from 'axios'

export const AuthProtection = (props) => {
  const history = useHistory()
  const ProtectedTemplate = props.component
  const [loading, setLoading] = React.useState(true)

  React.useEffect(()=>{
    const checkAuthStatus = async () => {
      if (Auth.getAuth()) {
        try {
          // 调用后端需要鉴权的接口校验Session有效性,后端需新增对应接口并添加auth:sanctum中间件
          await axios.get('http://localhost:8000/api/user', {
            withCredentials: true,
            headers: { 'Accept': 'application/json' }
          })
          setLoading(false)
        } catch (err) {
          // 校验失败说明Session已过期,清空状态跳登录页
          Auth.signout()
          history.push("/login")
        }
      } else {
        history.push("/login")
      }
    }
    checkAuthStatus()
  }, [history])

  if (loading) return <div>加载中...</div>

  return (
    <div>
      <ProtectedTemplate/>
    </div>
  )
}

3. 后端配置校验(Laravel端)

确保以下配置正确:

  • config/cors.php中paths包含你的路由路径,supports_credentials设为true,allowed_origins配置你的前端域名(如http://localhost:3000)
  • config/sanctum.php中stateful配置项添加你的前端域名(不带http/https前缀,如localhost:3000)
  • 校验用的/api/user路由添加auth:sanctum中间件

4. 冗余代码优化(可选)

login.js中无需手动获取拼接X-XSRF-TOKEN请求头,axios开启withCredentials: true后会自动读取cookie中的XSRF-TOKEN并携带,可删除对应的手动拼接代码。另外localStorage.setItem("user-info")存储XSRF-TOKEN的逻辑也可删除,该值已自动存储在cookie中。

内容的提问来源于stack exchange,提问作者Syeda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:27:02