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

Laravel Sanctum搭配Angular出现CSRF令牌不匹配问题求助

解决Angular + Laravel Sanctum登录419 CSRF令牌不匹配问题
  • 手动指定X-XSRF-TOKEN请求头
    axios默认会自动读取XSRF-TOKEN Cookie并设置X-XSRF-TOKEN头,但偶尔会出现读取失败的情况。修改登录代码,在获取CSRF Cookie后手动提取并设置:

    login(){
      console.log('test');
       
      axios.get('/sanctum/csrf-cookie').then(response => {
        // 从Cookie中提取XSRF-TOKEN
        const xsrfToken = document.cookie.split('; ').find(row => row.startsWith('XSRF-TOKEN='))?.split('=')[1];
        axios.post('/login', {
          email: 'test@test.de',
          password: 'password'
        }, {
          headers: {
            'X-XSRF-TOKEN': decodeURIComponent(xsrfToken) // 解码URL编码的Cookie值
          }
        }) 
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error.response)
        })
    });
    }
    
  • 调整SESSION_DOMAIN配置
    将.env中的SESSION_DOMAIN改为.localhost(前缀加英文点),让不同端口的localhost源可共享Cookie:

    SESSION_DOMAIN=.localhost
    

    修改后执行缓存清理命令:

    php artisan config:clear
    php artisan cache:clear
    
  • 确认登录路由的中间件组
    检查login路由是否注册在web中间件组下。若路由在api组,需确保EnsureFrontendRequestsAreStateful中间件正常处理CSRF验证,或直接将登录路由移至web组(web组包含VerifyCsrfToken,与Sanctum的CSRF机制兼容)。

  • 强制清除浏览器缓存与Cookie
    打开浏览器开发者工具(F12),切换至Application标签,删除localhost相关的所有Cookie,重启浏览器后重新测试。

  • 优化axios实例配置
    将axios的全局配置移至单独文件,确保withCredentials在所有请求前生效,避免组件内部配置时机问题:

    // 创建axios实例文件(如src/services/api.ts)
    import axios from 'axios';
    
    const api = axios.create({
      baseURL: 'http://localhost:8000',
      withCredentials: true
    });
    
    export default api;
    

    组件中导入该实例使用:

    import api from '../services/api';
    
    // ...
    
    login(){
      console.log('test');
       
      api.get('/sanctum/csrf-cookie').then(response => {
        api.post('/login', {
          email: 'test@test.de',
          password: 'password'
        }) 
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error.response)
        })
    });
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:57:50