Vue SPA刷新时如何验证Laravel Sanctum会话登录状态?
Vue.js + Laravel Sanctum 会话式SPA刷新验证登录状态方案
因为你用的是基于会话的Sanctum认证(仅靠laravel_session Cookie),刷新页面时验证登录状态的核心逻辑很直接:前端在页面初始化时调用后端的用户信息接口,后端通过Cookie对应的会话判断用户是否登录。
步骤1:后端添加用户信息接口
在Laravel的routes/api.php中添加一个受Sanctum保护的路由,用于返回当前登录用户的信息:
use Illuminate\Http\Request; Route::middleware('auth:sanctum')->get('/user', function (Request $request) { // 会话有效则返回用户模型,无效则自动返回401 return $request->user(); });
这个路由会自动检查请求中的laravel_session Cookie,若会话有效且用户已登录,就返回用户数据;否则抛出401未授权异常。
步骤2:前端配置axios
确保axios请求自动携带Cookie,在你的Vue项目的axios配置文件(比如src/utils/axios.js)中开启withCredentials:
import axios from 'axios'; axios.defaults.baseURL = 'http://你的Laravel后端域名'; axios.defaults.withCredentials = true; // 关键:让请求携带Cookie export default axios;
步骤3:前端初始化时验证状态
用状态管理工具(Pinia或Vuex)保存登录状态,在页面加载时调用用户接口更新状态。以下是Pinia的示例:
1. 创建Auth Store
// src/stores/auth.js import { defineStore } from 'pinia'; import axios from '@/utils/axios'; export const useAuthStore = defineStore('auth', { state: () => ({ user: null, isAuthenticated: false }), actions: { async fetchCurrentUser() { try { const res = await axios.get('/api/user'); this.user = res.data; this.isAuthenticated = true; } catch (err) { // 接口返回401时重置状态 this.user = null; this.isAuthenticated = false; } } } });
2. 在App初始化时调用
在App.vue的挂载钩子中触发验证:
<script setup> import { useAuthStore } from '@/stores/auth'; import { onMounted } from 'vue'; const authStore = useAuthStore(); onMounted(() => { // 页面刷新后立即验证用户状态 authStore.fetchCurrentUser(); }); </script>
3. 路由守卫增强验证(可选)
如果有需要登录才能访问的页面,可在路由守卫中先验证状态再跳转:
// src/router/index.js import { createRouter, createWebHistory } from 'vue-router'; import { useAuthStore } from '@/stores/auth'; const routes = [ { path: '/', component: () => import('@/views/Home.vue') }, { path: '/dashboard', component: () => import('@/views/Dashboard.vue'), meta: { requiresAuth: true } // 标记需要登录 }, { path: '/login', component: () => import('@/views/Login.vue') } ]; const router = createRouter({ history: createWebHistory(), routes }); router.beforeEach(async (to, from, next) => { const authStore = useAuthStore(); // 未验证过状态时先调用接口 if (!authStore.isAuthenticated && authStore.user === null) { await authStore.fetchCurrentUser(); } // 需登录但未登录时跳转到登录页 if (to.meta.requiresAuth && !authStore.isAuthenticated) { next('/login'); } else { next(); } }); export default router;
关键配置检查
确保后端的这两个配置正确:
config/sanctum.php的stateful数组包含你的Vue应用域名:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost:3000,localhost:8000')),
config/cors.php开启凭证支持:
'supports_credentials' => true, 'allowed_origins' => ['http://localhost:3000'], // 你的Vue应用地址
这样每次刷新页面时,前端都会主动请求后端接口验证会话有效性,从而更新登录状态。
内容的提问来源于stack exchange,提问作者stalwart1014
相关产品推荐
相关产品推荐

