Create CloudFront Signed URL in 1 Minute

Assume we have

  • AWS Bucket: test-bucket
  • AWS Object: /test-file.jpg
  • AWS Cloudfront: https://test-cdn.cloudfront.net/

Assume the Cloudfront has Original associated with the bucket, let's create signed URL for the file for restricted access.

Step 1 Generate RSA Key Pair for CloudFront

Create private key firstly.

openssl genrsa -out private_key.pem 2048

Extract public key from private key.

openssl rsa -pubout -in private_key.pem -out public_key.pem

Create key group at CloudFront according here, assume the public key ID is test-public-id.

Step 2 Construct Policy for S3 Object

Do not mess up with the Policy CloudFront at panel, the Policy here means the content of signed URL.

Create a JSON text file as below and save it to /tmp/test-policy.txt

{
    "Statement":[
        {
            "Resource":"https://test-cdn.cloudfront.net/test-file.jpg",
            "Condition":{
                "DateLessThan":{
                    "AWS:EpochTime":1649815417
                }
            }
        }
    ]
}

Step 3 Create Signature

Use one line command to generate signed signature for the URL.

cat /tmp/test-policy.log | tr -d "\n" | tr -d " \t\n\r" | openssl sha1 -sign private_key.pem | openssl base64 -A | tr -- '+=/' '-_~'

It would print text test-signature at console which is the signature part of final URL.

Step 4 Construct URL

The URL would be

https://test-cdn.cloudfront.net/test-file.jpg?Expires=1649815417&Signature={test-signature}&Key-Pair-Id={test-public-id}

Done.

 

posted on 2022-04-12 11:07  Bo Schwarzstein  阅读(149)  评论(0编辑  收藏  举报