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

Laravel Echo认证请求未携带Cookie至请求头,如何解决?

解决Laravel Echo未发送Cookie到broadcasting/auth的问题
  • 别手动设置Cookie请求头,浏览器会根据withCredentials自动处理Cookie的发送,手动设置大概率会被浏览器的安全机制拦截,尤其是跨域场景下。
  • 确保后端CORS配置允许携带凭证,同时指定具体的前端域名(不能用*)。

修改后的前端代码

window.Echo = new Echo({
  broadcaster: 'reverb',
  wsHost: 'localhost',
  key: 'yn0yitpyoptuuqiyjrhm',
  wsPort: 8080,
  wssPort: 8080,
  forceTLS: false,
  authEndpoint: 'http://localhost:8000/broadcasting/auth',
  headers: {
    Authorization: `Bearer ${token}`,
    // 移除手动添加的Cookie字段
  },
  withCredentials: true,
  enabledTransports: ['ws', 'wss'],
});

后端Laravel CORS配置调整

修改config/cors.php文件:

return [
    'paths' => ['api/*', 'broadcasting/auth'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['http://localhost:8080'], // 替换成你的前端实际域名/端口
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true, // 必须设为true,允许携带凭证
];

关键说明

  1. withCredentials: true是核心,它告诉浏览器在跨域请求中携带Cookie等凭证信息。
  2. 后端必须开启supports_credentials,同时allowed_origins不能用通配符,否则浏览器会拒绝发送Cookie。
  3. 浏览器只会自动发送与authEndpoint域名匹配的Cookie,确保前端页面的Cookie是后端设置的对应域名下的凭证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:42:38