首页 > 解决方案 > AWS S3 文件(从 AWS Lambda 函数重定向)响应 CORS preflight OPTIONS 请求并出现 403 错误

问题描述

我将 AWS S3 存储桶配置为具有以下 CORS 配置的静态网站:

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

我还有一个 Lambda 函数,可以重定向到上述 S3 存储桶上的特定页面。这是代码的要点:

module.exports.endPoint = (event, context, callback) => {
  // Do some cool processing and on success:
  redirectToUrl(303, 's3-bucket.amazon.com/page.html', callback);
}

function redirectToUrl(statusCode, url, callback) {
    const response = {
        statusCode: statusCode,
        headers: {
            Location: url,
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json'
        },
        body: '',
    };

    console.log('Redirecting with status code ' + statusCode + ' to ' + url);

    callback(null, response);
}

我可以使用代码中的相同 URL 直接从浏览器访问 S3 HTML 页面。是的,API 域与 S3 域不同:

api.domain.com --> initiates the request (redirection)
sub.domain.com/page.html --> requested resource (redirection target)

服务端响应 CORS preflight OPTIONS 请求报 403 错误,浏览器报如下错误信息:

从源“null”访问“S3 文件”处的 XMLHttpRequest(从“API 端点”重定向)已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许来源”请求的资源上存在标头。

我最初通过在我的 serverless.yml 中添加以下行来使用无服务器框架设置站点:

SiteBucket:
      Type: AWS::S3::Bucket
      Properties:
        AccessControl: PublicRead
        BucketName: ${self:custom.siteName}
        WebsiteConfiguration:
          IndexDocument: index.html
          ErrorDocument: error.html
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
                - GET
                - HEAD
              AllowedOrigins:
                - "*"
              MaxAge: 3000
    SiteBucketPolicy:
      Type: "AWS::S3::BucketPolicy"
      DependsOn: "SiteBucket"
      Properties:
        Bucket: ${self:custom.siteName}
        PolicyDocument:
          Statement:
            - Effect: Allow
              Principal: "*"
              Action:
                - "s3:GetObject"
              Resource:
                - "arn:aws:s3:::${self:custom.siteName}/*"

通过无服务器框架创建存储桶并看到 CORS 错误后,我在 S3 上手动完成了 CORS 策略,但没有成功。

还值得注意的是,S3 站点是使用 CloudFront Distribution 设置的,但我不确定这是否会有所不同。

这应该是一个简单的解决方法,但事实证明它非常困难。请帮忙。

标签: amazon-web-servicesamazon-s3cors

解决方案


这不应该包含正确的 URL:

redirectToUrl(303, 's3-bucket.amazon.com/page.html');

我认为将其更改为以下内容可能会解决您的问题:

redirectToUrl(303, 'https://s3-bucket.amazon.com/page.html');

推荐阅读