AWSCloudfrontAPI在浏览器上可以工作,但通过.netHttpClient出现403错误。
创始人
2024-09-24 08:00:48
0

这可能是因为缺少AWS签名,需要在HttpClient的请求头中添加签名信息。以下是实现此操作的示例代码:

using Amazon;
using Amazon.CloudFront;
using Amazon.CloudFront.Model;
using Amazon.Runtime;

// ... other code ...

void CallCloudFrontApiWithHttpClient()
{
    var accessKey = "your_aws_access_key";
    var secretKey = "your_aws_secret_key";
    var distributionId = "your_cloudfront_distribution_id";
    var resourceKey = "your_resource_key";

    var client = new HttpClient();
    var sigHandler = new AWS4SignHandler(accessKey, secretKey, RegionEndpoint.USEast1);
    var signedHeaders = sigHandler.SignHeaders(new Uri($"http://{distributionId}.cloudfront.net/{resourceKey}"), "GET");
    foreach (var header in signedHeaders)
    {
        client.DefaultRequestHeaders.Add(header.Key, header.Value);
    }

    var response = client.GetAsync($"http://{distributionId}.cloudfront.net/{resourceKey}").Result;
    var content = response.Content.ReadAsStringAsync().Result;

    // ... process response content ...
}

class AWS4SignHandler
{
    private readonly string accessKey;
    private readonly string secretKey;
    private readonly RegionEndpoint region;
    private const string algorithm = "AWS4-HMAC-SHA256";

    public AWS4SignHandler(string accessKey, string secretKey, RegionEndpoint region)
    {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.region = region;
    }

    public IDictionary SignHeaders(Uri endpointUri, string httpMethod)
    {
        var nowUtc = DateTime.UtcNow;
        var requestHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase);

        // Host header is required
        requestHeaders.Add("host", endpointUri.Host);

        // Date header is required
        var dateString = nowUtc.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
        requestHeaders.Add("x-amz-date", nowUtc.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture));

        // Authorization header is required
        var canonicalRequest = GetCanonicalRequest(endpointUri, httpMethod, requestHeaders, string.Empty);
        var stringToSign = GetStringToSign

相关内容

热门资讯

教程攻略!微乐自建房辅助工具,... 教程攻略!微乐自建房辅助工具,微乐自建房脚本免费入口(开挂自建房)app所有人都在同一条线上,像星星...
重大通报!微乐自建房辅助工具免... 重大通报!微乐自建房辅助工具免费app,微乐家乡麻将自建房辅助app(开挂自建房)教程1、重大通报!...
推荐一款!微信微乐自建房辅助工... 推荐一款!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)攻略进入游戏-大厅左侧-...
推荐一款!微乐自建房辅助工具神... 推荐一款!微乐自建房辅助工具神器,微乐小程序免费黑科技(开挂自建房)器1、金币登录送、破产送、升级送...
总算清楚!微信微乐自建房辅助工... 总算清楚!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)app1)微乐家乡麻将自...
重要通知!微乐自建房辅助工具神... 重要通知!微乐自建房辅助工具神器,微乐家乡麻将自建房辅助app(开挂自建房)方法1、在微乐家乡麻将自...
热点推荐!微信微乐自建房辅助工... 热点推荐!微信微乐自建房辅助工具,微乐自建房脚本免费入口(开挂自建房)app微信微乐自建房辅助工具能...
2024教程!微乐自建房辅助工... 2024教程!微乐自建房辅助工具神器,微乐自建房脚本免费入口(开挂自建房)脚本1、微乐自建房辅助工具...
记者揭秘!微乐自建房辅助工具神... 记者揭秘!微乐自建房辅助工具神器,微乐自建房脚本免费入口(开挂自建房)攻略;1、任何微乐自建房辅助工...
玩家实测!微乐自建房辅助工具插... 玩家实测!微乐自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)器1、微乐家乡麻将自建房...