Clickjacking Protection

    Suppose an online store has a page where a logged in user can click “Buy Now” topurchase an item. A user has chosen to stay logged into the store all the timefor convenience. An attacker site might create an “I Like Ponies” button on oneof their own pages, and load the store’s page in a transparent iframe such thatthe “Buy Now” button is invisibly overlaid on the “I Like Ponies” button. If theuser visits the attacker’s site, clicking “I Like Ponies” will cause aninadvertent click on the “Buy Now” button and an unknowing purchase of the item.

    Modern browsers honor the X-Frame-Options HTTP header that indicates whetheror not a resource is allowed to load within a frame or iframe. If the responsecontains the header with a value of then the browser will onlyload the resource in a frame if the request originated from the same site. Ifthe header is set to DENY then the browser will block the resource fromloading 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.

    This middleware is enabled in the settings file generated by.

    By default, the middleware will set the X-Frame-Options header toDENY for every outgoing HttpResponse. If you want any other value forthis header instead, set the X_FRAME_OPTIONS setting:

    Changed in Django 3.0:The default value of the setting was changedfrom to DENY.

    To set the X-Frame-Options header on a per view basis, Django provides thesedecorators:

    Note that you can use the decorators in conjunction with the middleware. Use ofa decorator overrides the middleware.

    The X-Frame-Options header will only protect against clickjacking in amodern browser. Older browsers will quietly ignore the header and need otherclickjacking prevention techniques.

    • Internet Explorer 8+
    • Edge
    • Firefox 3.6.9+
    • Opera 10.5+
    • Chrome 4.1+