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

向Cloudfront发送Fetch GET请求时未携带Cookie头,原因何在?

问题:Chrome/Brave中Stimulus控制器发起的Cloudfront请求未携带签名Cookie

背景

我正在通过Stimulus控制器向Cloudfront发送带签名Cookie的Fetch GET请求,以获取受保护的HLS内容。目前S3、Cloudfront、Rails服务端及客户端配置理论上均正确,但Cookie始终未随请求发送。

环境信息

  • Cloudfront URL:https://netflix.tonyfromtokyo.online/mm57enm1nx2u91ztntbu2idxxror/HLS/mm57enm1nx2u91ztntbu2idxxror.m3u8
  • 客户端URL:http://tonyfromtokyo.online:3000/movies/298486374,已修改/etc/hosts将tonyfromtokyo.online指向127.0.0.1,避免用localhost:3000发起请求
  • 浏览器无CORS错误,已配置允许http://tonyfromtokyo.online:3000的跨域请求

Cloudfront配置

  • CORS设置:
    Cloudfront CORS配置
  • 响应头设置:
    Cloudfront响应头配置

Rails服务端Cookie设置代码

cookies[key] = {
  value: value,
  domain: :all
}

Cookie已在浏览器中正确设置:
浏览器中已设置的Cookie

客户端Stimulus控制器代码

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="video-player"
export default class extends Controller {
  static targets = [ "video" ]
  static values = { videoUrl: String }

  connect() {
    fetch(this.videoUrlValue, { credentials: 'include' }) // 无Cookie发送

    // 配置Hls.js携带Cookie
    const config =
      {
          xhrSetup: function (xhr, url)
          {
            xhr.withCredentials = true; // 无Cookie发送
          },
          fetchSetup: function (context, initParams)
          {
            console.log("fetchSetup");
              // 跨域请求携带Cookie
              initParams.credentials = 'include';
              return new Request(context.url, initParams);
          },
      };

    if (Hls.isSupported()) {
      console.log("HLS supported");
      var hls = new Hls(config);

      hls.loadSource(this.videoUrlValue);
      hls.attachMedia(this.videoTarget);
      this.videoTarget.play();
    } else if (this.videoTarget.canPlayType('application/vnd.apple.mpegurl')) {
      this.videoTarget.src = this.videoUrlValue;
      this.videoTarget.addEventListener('canplay',function() {
        this.videoTarget.play();
      });
    }
  }
}

问题现象

  • 请求返回403错误,请求详情显示未携带Cookie:
    请求错误响应
    请求详情
  • 直接在浏览器地址栏访问Cloudfront URL时,Cookie能正常传递并获取内容:
    直接访问成功

浏览器兼容性验证

  • Firefox ✅:Cookie正常携带,可获取内容
  • Safari ✅:Cookie正常携带,可获取内容
  • Chrome ❌:Cookie未携带,返回403
  • Brave ❌:Cookie未携带,返回403

求解决Chrome和Brave中Cookie无法随请求发送的问题,谢谢。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:03:22