Search code examples
djangogoogle-cloud-cdn

How to configure django to generate signed urls for media files with Google Cloud CDN?


I am working on a project that requires load media files from Google Cloud CDN. Currently, I am loading the files in the form of urls - cdn.mydomain.com/image.jpg . But this requires to provide public access to the object. I need to generate signed url for secure access of these resources. I have checked django-storages. It provides signed url straight from the storage bucket but does not say anything about signed urls for CDN. How do I generate signed urls for Google Cloud CDN inside django and keep using the django-storages library?


Solution

  • I ended up writing a storage backend. The settings.CUSTOM_DOMAIN is the address of the CDN. My backend code is as follows -

    class CustomGoogleCloudStorage(GoogleCloudStorage):
        custom_domain = settings.CUSTOM_DOMAIN
    
        def make_url(self, name):
            host = "https://" + self.custom_domain
            return urllib.parse.urljoin(host, name)
    
        def url(self, name):
            name = self._normalize_name(name)
            url = self.make_url(name)
            key_name, base64_key = get_storage_key()
            expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1) #put your desired time here
            return sign_url(url, key_name, base64_key, expiration_time)
    

    The sign_url function is taken from GCP's github.