Search code examples
c#amazon-s3amazon-cloudfront

How do I use C# to get a signed URL from CloudFront?


There are several similar questions but not one quite the same:

We have an S3 bucket with CloudFront on it configured to use signedURLs. I can use the command line to generate a signed URL and access it. When I try to do this via C# the signed URL generated is not valid.

This is the command line which returns a valid url:

aws cloudfront sign --url https://MyPath.com/testfile.txt --key-pair-id "keypairIDvalue" --private-key file://bas_key.pem --date-less-than 2022-01-01

The code is this:

static void Main(string[] args)
{
    // technique 1
    string policyDoc = Amazon.CloudFront.AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
        @"https://MyPath/testfile.txt",
        DateTime.Today.AddDays(+4),
        "myIPAddress");

    string signurl = Amazon.CloudFront.AmazonCloudFrontUrlSigner.SignUrl(
        @"https://MyPath/testfile.txt", 
        "KeypairID", 
        new StreamReader(@"c:\keys\Bas_key.pem"), 
        policyDoc);

    // the signurl does not work

    // technique 2
    string newurl = Amazon.CloudFront.AmazonCloudFrontUrlSigner.GetCustomSignedURL(
        @"https://MyPath/testfile.txt",
        new StreamReader(@"c:\keys\Bas_key.pem"),
        "KeypairID",
        DateTime.Today.AddDays(4),
        DateTime.Today.AddDays(-1),
        "MyIPAddress");
        
    // newurl is different to signurl but also does not work

    Console.WriteLine(newurl);
}

Most examples I have seem to have a lot of extra code to do various bits and bobs but here everything is setup and configured. I just need the API command to get the URL, the documentation seems to imply this is an expected way of doing this but I cannot get it to work. Neither of the above techniques work.

Can anyone see what I have done wrong?


Solution

  • Fixed it!

    The working code is this!

    static void Main(string[] args)
    {
        // technique 1
        string policyDoc = Amazon.CloudFront.AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
            null,
            DateTime.Today.AddDays(+1),
            null);
    
        string signurl = Amazon.CloudFront.AmazonCloudFrontUrlSigner.SignUrl(
            @"https://MyPath/testfile.txt", 
            "KeypairID", 
            new StreamReader(@"c:\keys\Bas_key.pem"), 
            policyDoc);
    
         Console.WriteLine(signurl);
    }