【发布时间】:2019-05-31 16:23:33
【问题描述】:
我有一个 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错误,浏览器报如下错误信息:
在“S3 文件”处访问 XMLHttpRequest(从“API 端点”重定向) CORS 策略已阻止来自原点“null”:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
我最初通过在 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,但我不确定这是否会有所不同。
这应该很容易解决,但事实证明它非常困难。请帮忙。
【问题讨论】:
-
如标题所述,是403。
-
有同样的问题。你有想过吗?
标签: amazon-web-services amazon-s3 cors