我看到了 S3 对象的预签名 URL。是否可以为 API 网关创建预签名 URL。我已经阅读了文档。我正在使用.NET。我想知道是否有 .NET 库可用于为网关 API 创建预签名请求。
问题
我有类似这样的
GET
API,我们的客户偶尔会调用该 API。他们使用的旧工具仅支持 https://xxxxxx.execute-api.us-east-1.amazonaws.com/dev/pets?type=dog&page=1
。所以我想创建一个预签名 URL(到期时间短)并在他们要求时提供给他们。对于每个客户,我已经有 GET
用户及其各自的 IAM
和 accesskey
托管端点生成 SigV4 签名的 URL。通常,您需要在授权请求标头中发送 SigV4 签名。如果您的客户愿意发送标头,这里是您可以尝试使用 .NET 的一个示例库,它会创建一个带有签名标头的 HTTP 请求。 如果您的客户无法发送授权标头或无法使用上述库,那么您可以将签名转换为查询字符串格式并向他们提供预签名的 URL。
This AWS 文档提供了有关如何生成查询字符串 URL 的 Python 示例。现在,您可以使用 python 示例并使用以下示例转换为基于 .NET 的代码。
secretkey
完整端点变为 -
https://myApiId.execute-api.us-east-1.amazonaws.com/dev/myApigNodeJS?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20190104%2Fus-east- 1%2Fexecute-api%2Faws4_request&X-Amz-Date=20190104T190309Z&X-Amz-SignedHeaders=主机&X-Amz-Signature=7b830fce28f7800b3879a25850950f6c4247dfdc07775b6952295fa2fff03f 7f注意 -
此示例代码引用了我上面给出的
public string GetSig4QueryString(string host, string service, string region)
{
var t = DateTimeOffset.UtcNow;
var amzdate = t.ToString("yyyyMMddTHHmmssZ");
var datestamp = t.ToString("yyyyMMdd");
var canonical_uri = "/dev/myApigNodeJS";
var canonical_headers = "host:" + host+"\n";
var signed_headers = "host";
var credential_scope = $"{datestamp}/{region}/{service}/aws4_request";
var canonical_querystring = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=" + WebUtility.UrlEncode(_access_key + "/" + credential_scope)
+ "&X-Amz-Date=" + amzdate + "&X-Amz-SignedHeaders=" + signed_headers;
Console.WriteLine("canonical_querystring");
Console.WriteLine(canonical_querystring);
var payload_hash = Hash(new byte[0]);//No Payload for GET
var canonical_request = new StringBuilder();
canonical_request.Append("GET\n");
canonical_request.Append(canonical_uri + "\n");
canonical_request.Append(canonical_querystring + "\n");
canonical_request.Append(canonical_headers + "\n");
canonical_request.Append(signed_headers + "\n");
canonical_request.Append(payload_hash);
Console.WriteLine("canonical_request");
Console.WriteLine(canonical_request);
var string_to_sign = $"{algorithm}\n{amzdate}\n{credential_scope}\n" + Hash(Encoding.UTF8.GetBytes(canonical_request.ToString()));
Console.WriteLine("string_to_sign");
Console.WriteLine(string_to_sign);
var signing_key = GetSignatureKey(_secret_key, datestamp, region, service);
var signature = ToHexString(HmacSHA256(signing_key, string_to_sign));
var signed_querystring = canonical_querystring+"&X-Amz-Signature=" + signature;
return signed_querystring;
}
GetSig4QueryString("myApiId.execute-api.us-east-1.amazonaws.com","execute-api","us-east-1");
//Returned String --> X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential= AKIAIOSFODNN7EXAMPLE%2F20190104%2Fus-east-1%2Fexecute-api%2Faws4_request&X-Amz-Date=20190104T190309Z&X-Amz-SignedHeaders=host&X-Amz-Signature=7b830fce28f7800b3879a25850950f6c4247dfdc07775b6952295fa2fff03f7f