Clickjacking Protection
Suppose an online store has a page where a logged in user can click “Buy Now” to purchase an item. A user has chosen to stay logged into the store all the time for convenience. An attacker site might create an “I Like Ponies” button on one of their own pages, and load the store’s page in a transparent iframe such that the “Buy Now” button is invisibly overlaid on the “I Like Ponies” button. If the user visits the attacker’s site, clicking “I Like Ponies” will cause an inadvertent click on the “Buy Now” button and an unknowing purchase of the item.
Modern browsers honor the X-Frame-Options HTTP header that indicates whether or not a resource is allowed to load within a frame or iframe. If the response contains the header with a value of SAMEORIGIN
then the browser will only load the resource in a frame if the request originated from the same site. If the header is set to DENY
then the browser will block the resource from loading in a frame no matter which site made the request.
Django provides a few ways to include this header in responses from your site:
- A middleware that sets the header in all responses.
The X-Frame-Options
HTTP header will only be set by the middleware or view decorators if it is not already present in the response.
This middleware is enabled in the settings file generated by .
By default, the middleware will set the X-Frame-Options
header to DENY
for every outgoing HttpResponse
. If you want any other value for this header instead, set the X_FRAME_OPTIONS setting:
When using the middleware there may be some views where you do not want the header set. For those cases, you can use a view decorator that tells the middleware not to set the header:
Note
To set the X-Frame-Options
header on a per view basis, Django provides these decorators:
Note that you can use the decorators in conjunction with the middleware. Use of a decorator overrides the middleware.
The X-Frame-Options
header will only protect against clickjacking in a modern browser. Older browsers will quietly ignore the header and need .
- Internet Explorer 8+
- Edge
- Firefox 3.6.9+
- Opera 10.5+
- Chrome 4.1+
A complete list of browsers supporting X-Frame-Options
.