Skip to content

Codepolice

  • ⤫

Signing a request to set up a custom Amazon CloudFront Distribution with C#

Posted by Judy Alvarez Posted on February 28, 2022March 1, 2022
0

I love most of Amazon’s Web Services (AWS). CloudFront is their CDN service and they have an awesome feature that lets you host your files on your server and then Amazon automatically grabs the files from your server and puts them on their CDN. This makes it possible to easily modify your files without having to download them from some S3 bucket or something to make changes.

Unfortunately, Amazon doesn’t provide a UI to set up a “Custom Distribution” so you have to do a post request to a URL and send them some XML. It’s maybe not that hard but I think they could provide us with some simple page where you just paste some XML and sent the request. But you have to do it yourself. The only thing I had issues with was signing the request and getting your “encrypted” secret.

I found some code on Stack Overflow (as usual) and just made some small modifications to it for doing a Cloud Front setup request.

public static void InvalidateContent() {
    string httpDate = Helper.GetHttpDate();

    string AWSSecret = "YOUR SECRET";
    string AWSAccessKeyId = "YOUR ACCESS KEY";

    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = @"<DistributionConfig xmlns='http://cloudfront.amazonaws.com/doc/2010-11-01/'>
        <CustomOrigin>
            <DNSName>dist.alternativeto.net</DNSName>
            <HTTPPort>80</HTTPPort>
            <HTTPSPort>443</HTTPSPort>
            <OriginProtocolPolicy>match-viewer</OriginProtocolPolicy>
        </CustomOrigin>
        <CallerReference>" + httpDate + @"</CallerReference>
        <CNAME>static.alternativeto.net</CNAME>
        <Comment>My comments</Comment>
        <Enabled>true</Enabled>
        <Logging>
            <Bucket>mylogs.s3.amazonaws.com</Bucket>
            <Prefix>myprefix/</Prefix>
        </Logging>
    </DistributionConfig>";
    byte[] data = encoding.GetBytes(postData);

    // Prepare web request...
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-11-01/distribution");
    webRequest.Method = "POST";
    webRequest.ContentType = "text/xml";
    webRequest.Headers.Add("x-amz-date", httpDate);

    Encoding ae = new UTF8Encoding();
    HMACSHA1 signature = new HMACSHA1(ae.GetBytes(AWSSecret.ToCharArray()));

    string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));

    webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + AWSAccessKeyId + ":" + b64);

    webRequest.ContentLength = data.Length;

    Stream newStream = webRequest.GetRequestStream();
    // Send the data.
    newStream.Write(data, 0, data.Length);
    newStream.Close();
}

/// <summary>
/// Gets a proper HTTP date
/// </summary>
public static string GetHttpDate() {
    // Setting the Culture will ensure we get a proper HTTP Date.
    string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
    return date;
}
Categories: JavascriptTagged: asp .net ajax, asp net blogs, asp net boiler plate, asp net core cms, asp net core interview questions and answers for experienced, asp net core pdf viewer, asp net core web development, asp net crud, asp net environment variables, asp net in hindi, asp net msdn, asp net mvc generate pdf from view, asp net mvc interview questions and answers pdf, asp net pdf component, asp net pdf editor, asp net read excel file, asp net server, asp net table, asp net web pages, building microservices using asp net core 5.0 and docker, cheap asp net hosting, control state in asp net, convert pdf to html asp net, interview questions on asp net for experienced, jquery asp net, kudvenkat asp net core, passport authentication in asp net, shopping cart in asp net c# source code, textarea in asp net, validation for email in asp net

Post navigation

Previous Previous post: Use your IIS logs with WCAT
Next Next post: Debug and fix the z-index bug in IE6 and IE7

Related Posts

  • Playwright now offers a UI mode

    #​631 — March 24, 2023 Read on the Web JavaScript Weekly Speeding Up the JavaScript Ecosystem: npm Scripts — The latest in what has been a fascinating series on finding ‘low hanging fruit’ when it comes to performance in the JavaScript world. The author explains it best himself: “‘npm scripts’ are executed by JavaScript developers

    Posted by Posted on March 24, 2023
    0
  • Everyone’s coming for Node.js this week

    #​479 — March 23, 2023 Read on the Web 🔒  npm Granular Access Tokens Now Generally Available — The granular access token feature on the npm registry is now generally available, allowing you to restrict token access to specific packages, set expiration dates, limit access by IP range, and more. GitHub Automatic npm Publishing with GitHub

    Posted by Posted on March 23, 2023
    0
  • Transformers: JavaScript in Disguise

    #​630 — March 17, 2023 Read on the Web JavaScript Weekly 🤖  Transformers.js: Running ML Models in the Browser — Transformers are a type of machine learning model often used for natural language or visual processing and while running such models directly in the browser is in its infancy, Transformers.js opens up some ML models

    Posted by Posted on March 17, 2023
    0
  • Shell-free scripting from Node

    #​478 — March 16, 2023 Read on the Web Shell-Free Scripts with Execa 7.1 — Execa is a popular process execution library for Node and the latest version includes an interesting $ method feature for writing zx-style scripts with it, making it even more useful for shell scripting style usecases. ehmicky Turbowatch: File Change Detector and

    Posted by Posted on March 16, 2023
    0
  • New JavaScript features of the past few years

    #​629 — March 10, 2023 Read on the Web JavaScript Weekly JavaScript Features from the Past Few Years — Packed with examples, this post tackles the changes and tweaks to JavaScript and TypeScript over the past several years (some as far back as ES6/ES2015, like tagged template literals). Linus Schlumberger Astro’s 2023 Web Framework Performance Report —

    Posted by Posted on March 10, 2023
    0
  • Taking flight with Feathers 5

    #​477 — March 9, 2023 Read on the Web Feathers 5: The API and Real-Time App Framework — Feathers isn’t as well known as Nest or Fastify, say, but it’s a powerful and mature option if you want to spin up a Node CRUD app tied to a database and now it’s “TypeScript all the

    Posted by Posted on March 9, 2023
    0
Judy Alvarez

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Codepolice

  • Github
  • Atlassian
  • Flatlogic
  • Xero
  • Jetbrains
  • Figma
  • Playwright now offers a UI mode
  • Everyone’s coming for Node.js this week
  • Transformers: JavaScript in Disguise
  • Shell-free scripting from Node
  • New JavaScript features of the past few years
https://flatlogic.com/generator
COPYRIGHT © 2023 - Codepolice