When developing an application with crucial media, we can not share it openly in public. We need something that can resist users from misusing our media. For example, while developing a learning courses website/application. There will be so many images and video tutorials that as a developer we want to keep it secure. In this case, we are going to learn Signed URLs which have several advantages and will protect our media.
We are going to use Django as our backend and will be developing APIs with the help of the Django rest framework. And for storing our media files will be using AWS S3 buckets. If you already have a basic understanding of Django and AWS. This will be easy for you to understand.
I am going to show you two ways to secure media files.
1. Signed URLs
2. Signed Cookies
A signed URL is an URL that you can provide to your user to grant temporary access to a specific S3 object. A signed URL includes additional information, for example, expiration date and time, that gives you more control over access to your content. The URL needs to have some specific parameters like
Expires: The time that you want the URL to stop allowing access to the file.
Signature: The hashed and signed version of the policy statement.
Key-Pair-Id: Public key ID for the CloudFront public key whose corresponding private key you’re using to generate the signature.
Here’s an overview of how you configure CloudFront and Amazon S3 for signed URLs and how CloudFront responds when a user uses a signed URL to request a file.
➡️ In your CloudFront distribution, specify one or more trusted key groups, which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding private keys to sign the URLs.
➡️ Develop your application to determine whether a user should have access to your content and create signed URLs for the files or parts of your application that you want to restrict access to.
➡️ A user requests a file for which you want to require signed URLs.
➡️ Your application verifies that the user is entitled to access the file: they’ve signed in, they’ve paid for access to the content, or they’ve met some other requirement for access.
➡️ Your application creates and returns a signed URL to the user.
➡️ The signed URL allows the user to download or stream the content.
➡️ This step is automatic; the user usually doesn’t have to do anything additional to access the content. For example, if a user is accessing your content in a web browser, your application returns the signed URL to the browser. The browser immediately uses the signed URL to access the file in the CloudFront edge cache without any intervention from the user.
➡️ CloudFront uses the public key to validate the signature and confirm that the URL hasn’t been tampered with. If the signature is invalid, the request is rejected. If the signature is valid, CloudFront looks at the policy statement in the URL (or constructs one if you’re using a canned policy) to confirm that the request is still valid.
For example, if you specified a beginning and ending date and time for the URL, CloudFront confirms that the user is trying to access your content during the time period that you want to allow access. If the request meets the requirements in the policy statement, CloudFront does the standard operations: determines whether the file is already in the edge cache, forwards the request to the origin if necessary, and returns the file to the user.
Follow the below steps:
➡️ Create an S3 bucket on AWS and make it private for all public use except CloudFront.
➡️ Create Cloudfront for your bucket.
➡️ Create Django Project and do the necessary steps to make one API for getting one URL from the S3 bucket.
➡️ Now if you have the URL of a file stored in an S3 bucket and we wanted to convert this direct URL into a Signed URL by which we can access the file. Just need to add this code.
import os from datetime import datetime, timedelta from botocore.signers import CloudFrontSigner from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding def rsa_signer(message): key_data = os.getenv("CF_PEM_FILE").replace("\\n", "\n").encode() private_key = serialization.load_pem_private_key( key_data, password=None, backend=default_backend() ) return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1()) def get_pre_signed_url(url): if url: key_id = os.getenv("CF_KEY_PAIR") expire_date = datetime.now() + timedelta(minutes=5) cloud_front_signer = CloudFrontSigner(key_id, rsa_signer) # Create a signed url that will be valid until the specific expiry date # provided using a canned policy. # noinspection PyTypeChecker signed_url = cloud_front_signer.generate_presigned_url(url, date_less_than=expire_date) return signed_url return None
Explanation, rsa_signer method generates private for you from the Private key file. And get_pre_signed_url takes one argument URL, which is an S3 bucket URL, and will return the Signed URL.
Now,
CF_PEM_FILE
and
CF_KEY_PAIR
are the private pem file and key pair, which can get from AWS CloudFront.
CloudFront signed cookies allow you to control who can access your content when you don’t want to change your current URLs or when you want to provide access to multiple restricted files, for example, all of the files in the subscribers’ area of a website. This topic explains the considerations when using signed cookies and describes how to set signed cookies using canned and custom policies.
Here’s an overview of how you configure CloudFront for signed cookies and how CloudFront responds when a user submits a request that contains a signed cookie.
➡️ In your CloudFront distribution, specify one or more trusted key groups, which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding private keys to sign the URLs.
➡️ You develop your application to determine whether a user should have access to your content and, if so, to send three Set-Cookie headers to the viewer. (Each Set-Cookie header can contain only one name-value pair, and a CloudFront signed cookie requires three name-value pairs.) You must send the Set-Cookie headers to the viewer before the viewer requests your private content. If you set a short expiration time on the cookie, you might also want to send three more Set-Cookie headers in response to subsequent requests, so that the user continues to have access.
Typically, your CloudFront distribution will have at least two cache behaviours, one that doesn’t require authentication and one that does. The error page for the secure portion of the site includes a redirector or a link to a login page.
If you configure your distribution to cache files based on cookies, CloudFront doesn’t cache separate files based on the attributes in signed cookies.
➡️ A user signs in to your website and either pays for content or meets some other requirement for access.
➡️ Your application returns the Set-Cookie headers in the response, and the viewer stores the name-value pairs.
➡️ The user requests a file.
➡️ The user’s browser or other viewer gets the name-value pairs from step 4 and adds them to the request in a Cookie header. This is the signed cookie.
➡️ CloudFront uses the public key to validate the signature in the signed cookie and to confirm that the cookie hasn’t been tampered with. If the signature is invalid, the request is rejected.
If the signature in the cookie is valid, CloudFront looks at the policy statement in the cookie (or constructs one if you’re using a canned policy) to confirm that the request is still valid. For example, if you specified a beginning and ending date and time for the cookie, CloudFront confirms that the user is trying to access your content during the time period that you want to allow access.
If the request meets the requirements in the policy statement, CloudFront serves your content as it does for content that isn’t restricted: it determines whether the file is already in the edge cache, forwards the request to the origin if necessary, and returns the file to the user.
You can use the same Bucket and CloudFront as above or make a new setup by following the below steps:
➡️ Create an S3 bucket on AWS and make it private for all public use except CloudFront.
➡️ Create Cloudfront for your bucket.
➡️ Create Django Project and do the necessary steps to make one API for getting one URL from the S3 bucket.
➡️ Now if you have the URL of a file stored in an S3 bucket and we wanted to convert this direct URL into a Signed Cookie by which we can access the file. Just need to add this code.
import os import time import json import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding def _replace_unsupported_chars(some_str): """Replace unsupported chars: '+=/' with '-_~'""" return some_str.replace("+", "-") \ .replace("=", "_") \ .replace("/", "~") def _in_an_hour(): """Returns a UTC POSIX timestamp for one hour in the future""" return int(time.time()) + (60000*60) def rsa_signer(message, key): """ Based on https://boto3.readthedocs.io/en/latest/reference/services/cloudfront.html#examples """ private_key = serialization.load_pem_private_key( key, password=None, backend=default_backend() ) signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1()) signer.update(message) return signer.finalize() def generate_policy_cookie(url): """Returns a tuple: (policy json, policy base64)""" policy_dict = { "Statement": [ { "Resource": url, "Condition": { "DateLessThan": { "AWS:EpochTime": _in_an_hour() } } } ] } # Using separators=(',', ':') removes seperator whitespace policy_json = json.dumps(policy_dict, separators=(",", ":")) policy_64 = str(base64.b64encode(policy_json.encode("utf-8")), "utf-8") policy_64 = _replace_unsupported_chars(policy_64) return policy_json, policy_64 def generate_signature(policy, key): """Creates a signature for the policy from the key, returning a string""" sig_bytes = rsa_signer(policy.encode("utf-8"), key) sig_64 = _replace_unsupported_chars(str(base64.b64encode(sig_bytes), "utf-8")) return sig_64 def generate_cookies(policy, signature, cloudfront_id): """Returns a dictionary for cookie values in the form 'COOKIE NAME': 'COOKIE VALUE'""" return { "CloudFront-Policy": policy, "CloudFront-Signature": signature, "CloudFront-Key-Pair-Id": cloudfront_id } def generate_curl_cmd(url, cookies): """Generates a cURL command (use for testing)""" curl_cmd = "curl -v" for k, v in cookies.items(): curl_cmd += " -H 'Cookie: {}={}'".format(k, v) curl_cmd += " {}".format(url) return curl_cmd def generate_signed_cookies(url, cloudfront_id, key): policy_json, policy_64 = generate_policy_cookie(url) signature = generate_signature(policy_json, key) return generate_cookies(policy_64, signature, cloudfront_id) def get_signed_cookie(url_folder, url_exact): if url_folder: url_folder = os.getenv("CF_BUCKET_URL") + url_folder url_exact = os.getenv("CF_BUCKET_URL") + url_exact cookies = generate_signed_cookies(url_folder, os.getenv("CF_KEY_PAIR"), os.getenv("CF_PEM_FILE").replace("\\n", "\n").encode()) return generate_curl_cmd(url_exact, cookies)
Now, you just have to use get_signed_cookie Method for getting signed cookies data. As a signed cookie can work on any S3 folder so you have to pass two parameters here, one is the path of the folder you want to add a cookie, the second is the path of the actual file.
I have shown you both ways to secure your media files, Signed URL, and Signed Cookies. If you have any file that you want to secure, can use a signed URL except if there is a streaming file then you have to use Signed Cookies.
I am also sharing the GitHub repo with you if need any help with the demo project.
Django-signed-URLs
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork