javascript 如何使用AWS 4-HMAC-SHA 256对请求进行签名?

bvuwiixz  于 10个月前  发布在  Java
关注(0)|答案(1)|浏览(104)

我想从AWS STS服务获取临时凭据,但无论我尝试什么,我总是得到这个错误

<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
  <Error>
    <Type>Sender</Type>
    <Code>SignatureDoesNotMatch</Code>
    <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message>
  </Error>
  <RequestId>661e2bc1-d3cf-4383-9227-5db05a0fb4e3</RequestId>
</ErrorResponse>

字符串
我100%肯定我的凭据是正确的,我甚至尝试了它在 Postman 和它的工作,但我做错了什么?这是我的密码

import * as aws4 from 'aws4'

async getStsCredentials() {
    
  const awsCredentials = {
    accessKeyId: 'xxx',
    secretAccessKey: 'xxx',
    region: 'us-east-1', 
  };
  
  const params = {
    RoleArn: 'xxx', 
    RoleSessionName: 'test', 
    DurationSeconds: 3600, 
  };
  
  const endpoint = `https://sts.${awsCredentials.region}.amazonaws.com/?Version=2011-06-15&Action=AssumeRole&RoleSessionName=${params.RoleSessionName}&RoleArn=${encodeURIComponent(params.RoleArn)}&DurationSeconds=${params.DurationSeconds}`;
  
  const signedRequest = aws4.sign(
    {
      service: 'sts',
      region: awsCredentials.region,
      method: 'GET',
      host:`sts.${awsCredentials.region}.amazonaws.com`,
      path: endpoint,
    },
    awsCredentials
  );
  
  // Send the request
  fetch(endpoint, {
    headers:{
      'Authorization':signedRequest.headers.Authorization as string,
      'x-amz-date':signedRequest.headers['X-Amz-Date']as string
    }
  })
      .then((response) => response.text())
      .then((result) => console.log(result))
      .catch((error) => console.log('error', error));
}

wz1wpwve

wz1wpwve1#

如果您错误地计算了规范请求或要签名的字符串,则服务执行的签名验证步骤将失败,并显示您看到的错误消息。
错误响应包括规范化请求和服务计算的要签名的字符串。您可以将这些字符串与您计算的字符串进行比较。
您还可以验证您没有通过修改头部或请求的代理发送请求。

相关问题