AWS CloudFront签名的Cookie + S3可在REST客户端应用程序中使用,但不能在浏览器中使用 S3配置 CloudFront发行版

如何解决AWS CloudFront签名的Cookie + S3可在REST客户端应用程序中使用,但不能在浏览器中使用 S3配置 CloudFront发行版

我正在尽可能详细地说明这个问题,以便遇到相同问题的其他人都可以使用全面的资源来解决此问题并使其正常工作。

目标

目标是使用签名的Cookie,以便我的应用程序中经过身份验证的用户可以自由访问其任何文件,而无需签名URL。

S3和CloudFront配置

我敢肯定,其中大多数是正确的,但是为了提供完整的图片,我将包括我拥有的设置。

S3配置

我有一个存储桶,我们将其称为my-storage。它具有以下CORS配置:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

存储桶策略为:

{
    "Version": "2008-10-17","Statement": [
        {
            "Effect": "Allow","Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity xxx"
            },"Action": "s3:GetObject","Resource": "arn:aws:s3:::my-storage/*"
        },{
            "Effect": "Allow","Principal": "*","Resource": "arn:aws:s3:::my-storage/*","Condition": {
                "StringLike": {
                    "aws:Referer": "http://localhost:8080/*"
                }
            }
        }
    ]
}

本地主机例外是这样,因为HTTP cookie由于跨域问题而无法正常工作,所以我可以在本地构建/测试我的应用程序。

CloudFront发行版

我有一个使用该存储桶作为源的CloudFront发行版。为了这篇文章的缘故,我们将CNAME设为files.mysite.com。这是原始配置:

enter image description here

行为配置需要截图和发布,但重要的细节是:

  • 允许的HTTP方法:GET,HEAD,OPTIONS
  • 缓存和原始请求设置:使用缓存策略和原始请求策略
  • 缓存策略:Managed-CachingOptimized
  • 原始请求策略:Managed-CORS-S3Origin
  • 限制查看者访问权限:是
  • 受信任的签名者:自我

失眠的阳性测试结果(REST客户端)??

我正在使用Insomnia REST client进行测试,从等式中删除浏览器,看起来一切正常。

我向我的API请求返回签名的cookie,可以在响应标头中看到它:

date: Tue,25 Aug 2020 15:09:35 GMT
x-amzn-requestid: xxx
access-control-allow-origin: https://web.mysite.com
set-cookie: CloudFront-Policy=xxx; Domain=mysite.com; Path=/users/; HttpOnly; Secure
set-cookie: CloudFront-Key-Pair-Id=xxx; Domain=mysite.com; Path=/users/; HttpOnly; Secure
set-cookie: CloudFront-Signature=xxx; Domain=mysite.com; Path=/users/; HttpOnly; Secure
x-amz-apigw-id: xxx
vary: Origin
x-powered-by: Express
x-amzn-trace-id: Root=xxx;Sampled=1
access-control-allow-credentials: true
x-cache: Miss from cloudfront
via: 1.1 xxx.cloudfront.net (CloudFront)
x-amz-cf-pop: ORD52-C1
x-amz-cf-id: xxx

Insomnia将cookie存储在客户端中。然后,我向文件GET提出了https://files.mysite.com/users/xx/xx.mp3请求。我得到200响应和文件的二进制数据,没问题。标头显示了cookie是否已正确发送:

> GET /users/9dbb70d7-3d17-4215-8966-49815e461dee/audio/d76bb13d-0e1d-45dc-b7e5-9cb8fb6dee1a/workfile.mp3 HTTP/1.1
> Host: files.mysite.com
> User-Agent: insomnia/2020.3.3
> Cookie: CloudFront-Key-Pair-Id=xxx; CloudFront-Signature=xxx; CloudFront-Policy=xxx
> Origin: https://web.mysite.com
> Accept: */*

太好了!因此从理论上讲,这应该可行。

实际浏览器结果???

这是Web应用程序中发生的事情。我进行了身份验证,然后看到API请求传出以获取签名的Cookie:

GET https://api.mysite.com/private/get-signed-cookie

{
  "Response Headers (1.373 KB)": {
    "headers": [
      {
        "name": "access-control-allow-credentials","value": "true"
      },{
        "name": "access-control-allow-origin","value": "https://web.mysite.com"
      },{
        "name": "date","value": "Tue,25 Aug 2020 15:16:28 GMT"
      },{
        "name": "set-cookie","value": "CloudFront-Policy=xxx; Domain=mysite.com; Path=/users/; HttpOnly; Secure"
      },"value": "CloudFront-Key-Pair-Id=xxx; Domain=mysite.com; Path=/users/; HttpOnly; Secure"
      },"value": "CloudFront-Signature=xxx; Domain=mysite.com; Path=/users/; HttpOnly; Secure"
      },{
        "name": "vary","value": "Origin"
      },{
        "name": "via","value": "1.1 xxx.cloudfront.net (CloudFront)"
      },{
        "name": "x-amz-apigw-id","value": "xxx"
      },{
        "name": "x-amz-cf-id",{
        "name": "x-amz-cf-pop","value": "ORD52-C1"
      },{
        "name": "x-amzn-requestid",{
        "name": "x-amzn-trace-id",{
        "name": "x-cache","value": "Miss from cloudfront"
      },{
        "name": "X-Firefox-Spdy","value": "h2"
      },{
        "name": "x-powered-by","value": "Express"
      }
    ]
  }
}

在这一点上,值得注意的是,我在Firefox Dev Tools中看不到cookie!我只能假定它们没有存储。

enter image description here

当浏览器尝试通过CloudFront发行版访问某些内容时:

GET https://files.mysite.com/users/9dbb70d7-3d17-4215-8966-49815e461dee/audio/d76bb13d-0e1d-45dc-b7e5-9cb8fb6dee1a/workfile.mp3

我在此正文中收到403 Forbidden响应:

<?xml version="1.0" encoding="UTF-8"?><Error><Code>MissingKey</Code><Message>Missing Key-Pair-Id query parameter or cookie value</Message></Error>

可以肯定的是,请求标头没有显示发送Cookie的迹象:

{
  "Request Headers (535 B)": {
    "headers": [
      {
        "name": "Accept","value": "audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5"
      },{
        "name": "Accept-Encoding","value": "gzip,deflate,br"
      },{
        "name": "Accept-Language","value": "en-US,en;q=0.5"
      },{
        "name": "Connection","value": "keep-alive"
      },{
        "name": "Host","value": "files.mysite.com"
      },{
        "name": "Origin",{
        "name": "Range","value": "bytes=0-"
      },{
        "name": "Referer","value": "https://web.mysite.com/dashboard"
      },{
        "name": "User-Agent","value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:79.0) Gecko/20100101 Firefox/79.0"
      }
    ]
  }
}

我在这里想念什么?彼此交谈的所有URL都具有相同的域(发布cookie的API,Web客户端,CloudFront分发)。我很确定Express API具有正确的CORS配置:

router.use(
  cors({
    origin(origin,callback) {
      if (/\.mysite\.com$/.test(origin)) {
        callback(null,true);
      } else {
        callback(new Error('Not allowed by CORS'));
      }
    },credentials: true,}),);

我完全迷住了。任何帮助,将不胜感激!

解决方法

好的,因此有很多步骤可以解决此问题。我可能不会完全了解它们,但这是我更改/修复的问题:

客户端问题

客户端正在使用axios来获取二进制文件,并使用HTMLAudioElement来获取音频文件。两者都必须更新以发送凭据(cookie)。对于axios调用,为axios.get(url,{ withCredentials: true }),对于HTMLAudioElement,为audioEl.crossOrigin = 'use-credentials'。现在,这两个请求都会将HTTP cookie发送到CloudFront。

API网关更改

必须在此处设置一些CORS内容。对于这篇文章来说太深了,但是我正在使用无服务器框架来配置API网关,这使事情变得容易得多!在serverless.yml文件中,我必须进行一些更改:

          cors:
            origins:
              - https://localhost:8080
              - https://*.mysite.com
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
              - x-user-id # this is my own header I pass from the web client
            allowCredentials: true

这基本上设置了API网关飞行前OPTION端点,因此它返回正确的CORS标头。它将在API网关中创建此智能脚本以处理多个来源:

#set($origin = $input.params("Origin"))
#if($origin == "") #set($origin = $input.params("origin")) #end
#if($origin.matches("https://localhost:8080") || $origin.matches("https://.+[.]mysite[.]com")) #set($context.responseOverride.header.Access-Control-Allow-Origin = $origin) #end

同样,太深了,无法理解这个答案。但是使用无服务器的任何人都应该签出Serverless Framework。这节省了很多时间!

S3配置

必须修改S3的CORS配置。对上述配置的唯一更改是:

<AllowedOrigin>https://*.mysite.com</AllowedOrigin>

整个堆栈中的总体规则是,如果您使用的是Access-Control-Allow-Credentials: true,则不允许将原点设为*

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-