clickjacking.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. Clickjacking Protection Middleware.
  3. This module provides a middleware that implements protection against a
  4. malicious site loading resources from your site in a hidden frame.
  5. """
  6. from django.conf import settings
  7. class XFrameOptionsMiddleware(object):
  8. """
  9. Middleware that sets the X-Frame-Options HTTP header in HTTP responses.
  10. Does not set the header if it's already set or if the response contains
  11. a xframe_options_exempt value set to True.
  12. By default, sets the X-Frame-Options header to 'SAMEORIGIN', meaning the
  13. response can only be loaded on a frame within the same site. To prevent the
  14. response from being loaded in a frame in any site, set X_FRAME_OPTIONS in
  15. your project's Django settings to 'DENY'.
  16. Note: older browsers will quietly ignore this header, thus other
  17. clickjacking protection techniques should be used if protection in those
  18. browsers is required.
  19. http://en.wikipedia.org/wiki/Clickjacking#Server_and_client
  20. """
  21. def process_response(self, request, response):
  22. # Don't set it if it's already in the response
  23. if response.get('X-Frame-Options', None) is not None:
  24. return response
  25. # Don't set it if they used @xframe_options_exempt
  26. if getattr(response, 'xframe_options_exempt', False):
  27. return response
  28. response['X-Frame-Options'] = self.get_xframe_options_value(request,
  29. response)
  30. return response
  31. def get_xframe_options_value(self, request, response):
  32. """
  33. Gets the value to set for the X_FRAME_OPTIONS header.
  34. By default this uses the value from the X_FRAME_OPTIONS Django
  35. settings. If not found in settings, defaults to 'SAMEORIGIN'.
  36. This method can be overridden if needed, allowing it to vary based on
  37. the request or response.
  38. """
  39. return getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN').upper()