YouTube & Django security middleware
2022-03-20Django's defaults security settings can prevent from embedding Youtube videos.
TL;DR
When embedding Youtube videos in a Django project, use:
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
Want to know more? Read on.
On a recent Wagtail project, I embedded YouTube music videos using the embed feature (based on oEmbed specification)
Others had reported this issue before for copyrighted content or video without embedding allowed. The content I was trying to embed is definitely copyrighted and with embedding allowed.
In a Codepen I could display the video properly.
I looked at the project settings and couldn’t see any causes expect from the Django Security Middleware
.
I turned it off and I could see the video :tada:.
It seemed that some security settings didn’t let the browser load the video.
Wagtail applies the default configuration from Django Security Middleware
, it’s the standard way of bootstrapping a new project through the official wagtail start
command.
I looked at the Django Security Middleware
documentation and various security settings I could tweak.
After toggling settings one by one, I found the culprit: SECURE_REFERER_POLICY
.
This setting relates to the Referer HTTP header which gives information about the page making a request (i.e. the request’s origin).
Moreover, this setting directly interfaces the Referrer-Policy HTTP header which controls how much information the Referer
HTTP header contains.
The default value for Django is same-origin
, which sends information only for request on the same domain. In this case, a request to youtube.com
won’t send any Referer
HTTP header.
Youtube requires the Referer
HTTP header set when embedding some videos.
I ended up setting the following in my configuration:
# settings/base.py
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
Some possible reasons of why Youtube requires the Referer
HTTP header:
- Youtube restricts Copyrighted content to some countries, it checks the origin website before sending the content.
- It’s possible to restrict the embedding of videos. This uses the
Referer
HTTP header to filter which websites can embed content.
Thanks to nobe4 for the rewrite proofreading.