使用AWS S3预签名URL获取资源时遭遇CORS错误
解决S3预签名URL的CORS访问问题
问题场景
我在.NET 8 WebAPI中使用AWSSDK.S3 NuGet包生成S3资源的预签名URL,代码如下:
public string CreatePreSignedUrl(string key, string userId) { try { var request = new GetPreSignedUrlRequest { BucketName = _bucketName, Key = $"{userId}/{key}", Expires = DateTime.UtcNow.AddMinutes(5) }; var result = _amazonS3Client.GetPreSignedURL(request); return result; } catch (AmazonS3Exception e) { // Log AWS S3 specific exceptions _logger.LogError($"An error occurred with AWS S3: {e.Message}"); return string.Empty; } catch (Exception e) { // Log other exceptions _logger.LogError($"An error occurred: {e.Message}"); return string.Empty; } }
前端用Next.js通过以下流程访问资源:
- 后端返回纯字符串形式的预签名URL
- 前端直接GET该URL
此时出现CORS错误:
Access to fetch at
'https://pictures-storage-dev.s3.eu-central-1.amazonaws.com/{rest-of-preSignedUrl}'
from origin 'https://localhost:3000' has been blocked by
CORS policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource. If an opaque response serves your needs, set the
request's mode to 'no-cors' to fetch the resource with CORS disabled.
Referrer Policy: strict-origin-when-cross-origin
手动访问该预签名URL正常,仅前端跨域访问时触发CORS限制。
解决方案
核心:配置S3存储桶的CORS策略
预签名URL直接指向S3存储桶的资源,因此CORS规则需要在S3存储桶本身上配置,而非后端WebAPI。
具体配置步骤
- 登录AWS控制台,进入S3服务,找到目标存储桶
pictures-storage-dev - 切换到权限标签页,找到跨域资源共享(CORS) 配置项
- 替换现有规则为以下JSON配置(根据实际需求调整):
[ { "AllowedHeaders": ["*"], "AllowedMethods": ["GET"], "AllowedOrigins": ["https://localhost:3000"], "ExposeHeaders": [] } ]
AllowedOrigins:添加你的前端域名,生产环境需替换为实际部署的域名(支持通配符如https://*.yourdomain.com,但不建议在生产环境用*)AllowedMethods:仅允许GET即可,因为预签名URL用于获取资源AllowedHeaders:设置为["*"]适配大部分前端请求场景,也可按需指定具体头
额外注意事项
- 配置生效可能需要几分钟,修改后请等待片刻再测试
- 若前端请求包含自定义头,需要在
AllowedHeaders中明确列出 - 不要在前端设置
mode: 'no-cors'(除非你不需要读取响应内容),这会导致响应变为不透明,无法正常处理资源
内容的提问来源于stack exchange,提问作者messerke
相关产品推荐
相关产品推荐

