我认为我必须忽略一些非常简单的东西,但是我只是无法发现它是什么。任何帮助将不胜感激!
概述
我一直在解决在浏览器中通过JavaScript访问AWS Cloud Directory服务的问题。我提出了我能想到的最简单的API请求(ListDirectories),但仍然无法正常工作。
代码
引用的SDK文件(aws-sdk-2.283.1.min.js)是从AWS JavaScript SDK Builder生成的,仅选择了Cloud Directory服务。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="aws-sdk-2.283.1.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
AWS.config.logger = console;
// instantiate a new Cloud Directory client
// providing: region, access key id, secret access key
const cloudDirectory = new AWS.CloudDirectory({region: 'ap-southeast-2', accessKeyId: 'xxxxxxxxxxxxxxxxxxxx', secretAccessKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' });
// call the list directories API
cloudDirectory.listDirectories()
.promise()
.then((response) => {
console.log('Test of Hardcoded Creds successful');
for (let i = 0, l = response.Directories.length; i < l; i++) {
console.log(response.Directories[i].Name);
}
}).catch((reason) => {
console.log('Test of Hardcoded Creds failed: ' + reason);
});
</script>
</body>
预期行为
对API的成功调用应导致在浏览器调试窗口中显示消息“测试硬编码Creds成功”,然后显示每个Cloud Directory的名称。
观察到的行为
浏览器调用https://clouddirectory.ap-southeast-2.amazonaws.com/amazonclouddirectory/2017-01-11/directory/list。这是HTTP OPTIONS请求,即检查CORS的预检。此请求失败,并显示HTTP 403 Forbidden错误代码。
响应消息为:
<MissingAuthenticationTokenException>
<Message>Missing Authentication Token</Message>
</MissingAuthenticationTokenException>
重复以下控制台输出:
OPTIONS https://clouddirectory.ap-southeast-2.amazonaws.com/amazonclouddirectory/2017-01-11/directory/list 403 (Forbidden)
handleRequest @ aws-sdk-2.283.1.min.js:5
...
(anonymous) @ test.html:17
test.html:1 Failed to load https://clouddirectory.ap-southeast-2.amazonaws.com/amazonclouddirectory/2017-01-11/directory/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
然后:
aws-sdk-2.283.1.min.js:2 [AWS clouddirectory undefined 0.416s 3 retries] listDirectories({})
test.html:24 Test of Hardcoded Creds failed: NetworkingError: Network Failure
结论
查看请求标头,我希望看到AWS Signature v4的Authorization标头。我认为这种缺失是问题的根源。因为我使用的是SDK,并且它应该为我执行签名,所以我怀疑这可能是实际的问题(否则,不仅是我,还会有更多的人遇到这种情况)。
已进行故障排除
在StackOverflow上有很多与此类似的问题,但它们用于访问S3或API网关。这不是一个相同的问题,因为对于S3和API网关,都可以为该服务设置CORS配置。就我所知,对于CloudDirectory,情况并非如此。